I try to repeat and learn more advanced uses and options when cutting trees with forks in the jungle of C. But foolishly I find an example which should be very easy as I have worked with forks before and even written some code, but i can't understand it fully.
Here comes :
main() {
if (fork() == 0) {
if (fork() == 0) {
printf("3");
}
else if ((wait(NULL)) > 0) {
printf("2");
}
}
else {
if (fork() == 0) {
printf("1");
exit(0);
}
if (fork() == 0) {
printf("4");
}
}
printf("0");
return 0;
}
Possible solutions are :
where 2, 5 and 6 are correct answers.
First of all, shouldn't there be four zeroes in the output? Second... How does one come to the solution at all? Been doing this on paper for almost an hour and I'm not even close to understanding why the given solution are more correct than the false ones (except for nr3 as it can't end with 2 since a 0 must follow).
Anyone with his forks in check who can offer some good explanation?
EDIT:
Found this here look at pdf's from 2009. Can people now stop making posts about this being a homework and actually try to help? If not please find some other topics to spend your time. Thanks !
fork() in C. Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.
When a process calls fork, it is deemed the parent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call.
If fork() returns a negative value, the creation of a child process was unsuccessful. fork() returns a zero to the newly created child process. fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types. h.
Parent process (main) must iterate the loop 3 times. Then printf is called. On each iteration of parent for-loop a fork() is called. After each fork() call, i is incremented, and so every child starts a for-loop from i before it is incremented.
I think there should be 4 zeroes, and that is what I see if I run your code...
A good way to analyse this is to draw a diagram like this one - I've shown the forks as *
with the parent continuing horizontally, and the child below, so that each individual process is on a separate line:
----*----*----*----0----exit (return from main)
| | |
| | +----4----0----exit (return from main)
| |
| +----1----exit (explicitly)
|
+-----*----wait----2----0----exit (return from main)
|
+----3----0----exit (return from main)
Now it's easy to see that, because of the wait()
, you must see 3
followed some time later by 0
, before seeing 2
followed by 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With