Reputation: 13
After a strong discusion with my friend, we decided to ask if our intuition is on the right path. The problem is with the fork() function or rather with the child processes. Here's the code:
int main()
{
int status;
if(!fork()) execl("pp1",NULL);
if(!fork()) execl("pp2",NULL);
if(!fork()) execl("pp3",NULL);
wait(&status);
return status;
}
The author explains that this program is going to create only 3 child processes, but when it come to the first child, it will enter the first "if" and execute pp1 as a new process but with the same pid as child, and that's ok. The problem is with the second and third child, how it will run this code. Our intuision is that we won't get to the second and third "if". Program pp1 will be run 3 times by all of the 3 children processes.
What do you think? What will be the result?
Upvotes: 1
Views: 340
Reputation: 1283
This code will execute pp1, then pp2 and finally pp3. Alright. But it might be a goot idea to verify the return value of execl too. If it fails, it won't exit (Yeah, the exec functions exit the running process).
But i don't know what you wanna do. But to launch binaries from a C programm (Even if you just wanna get the return value of this programm), it can (i say "can" ;) ) be better to use the 'system()' function. It returns the value of the programm passed in parameter and doesn't exit the programm after his execution, unlike the exec functions.
I'm just giving another solution. I'm not criticizing that one ;)
Upvotes: 0
Reputation: 157967
Note the return values of fork()
. From man 2 fork
:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropri‐ ately.
Meaning the child process receives 0
after successful fork. As !0
evaluates to true
the child execute execl
then, while the father steps forward to the next fork()
.
Upvotes: 2