c++ - using exec to execute a system command in a new process -
i trying spawn process executes system command, while own program still proceeds , 2 processes run in parallel. working on linux.
i looked online , sounds should use exec() family. doesn't work quite expected. example, in following code, see "before" being printed, ,but not "done".
i curious if issing anything?
#include <unistd.h> #include <iostream> using namespace std; main() { cout << "before" << endl; execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0); cout << "done" << endl; } [update]
thank guys comments. program looks this. works fine except @ end, have press enter finish program. not sure why have press last enter?
#include <unistd.h> #include <iostream> using namespace std; main() { cout << "before" << endl; int pid = fork(); cout << pid << endl; if (pid==0) { execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0); } cout << "done" << endl; }
you're missing call fork. exec replace current process image of new program. use fork spawn copy of current process. return value tell whether it's child or original parent that's running. if it's child, call exec.
once you've made change, appears need press enter programs finish. what's happening this: parent process forks , executes child process. both processes run, , both processes print stdout @ same time. output garbled. parent process has less child, terminates first. when terminates, shell, waiting it, wakes , prints usual prompt. meanwhile, child process still running. prints more file entries. finally, terminates. shell isn't paying attention child process (its grandchild), shell has no reason re-print prompt. more @ output get, , should able find usual command prompt buried in ls output above.
the cursor appears waiting press key. when do, shell prints prompt, , looks normal. far shell concerned, normal. have typed command before. have looked little strange, shell have executed because receives input keyboard, not child process printing additional characters screen.
if use program top in separate console window, can watch , confirm both programs have finished running before have press enter.
Comments
Post a Comment