Reputation: 13
I want execute another program in C program. Since I want use redirection, I use execl function to execute /bin/sh and pass the new command to it. Code is like this:
execl("/bin/sh", "/bin/sh", "-c", "/myprogram > a.out", NULL);
I know C program process will turn to be the shell(/bin/sh) process in the first stage. What confuses me is that whether the new shell process forks a new process to execute "/myprogram > a.out" or the shell process itself parses and turns to be "/myprogram > a.out".
I did a small test on this. Result seems to support the latter hypothesis. Test is like this:
I start a zsh on my computer, run the command echo $$
, result is 56341
. This shell's pid is 56341
$ echo $$
56341
Then run command /bin/sh -c "/Users/Jack/dead_loop"
in this shell. It does not return because the program is a forever loop.
$ /bin/sh -c "/Users/Jack/dead_loop"
█
The dead_loop source code is:
int main(){
while(1){
;
}
}
I start a new terminal and run command ps -ef|grep dead_loop
. Result shows that the dead_loop
program's parent process is the first shell process.
What I expect is that the dead_loop
program's parent process is another new shell process. So this "the shell process itself parses and turns to be /myprogram > a.out
" idea comes to my mind.
Upvotes: 0
Views: 542
Reputation: 409176
Remember that the exec
family of functions replaces the current process.
You must use fork
to create a new process to run exec
(if you want your program to continue).
And it's the same for the shell: It must also fork
a new process to call exec
for the programs it runs.
Upvotes: 1