Reputation: 4717
Sorry for this, just can't seem to make sense of what is going on in this little piece of C :
#include <stdio.h>
main()
{
int i;
if (fork()) { /* must be the parent */
for (i=0; i<1000; i++)
printf("\t\t\tParent %d\n", i);
}
else { /* must be the child */
for (i=0; i<1000; i++)
printf("Child %d\n", i);
}
}
As I understand it, it will print child 1000 times and parent 1000 times, but apparently it is much more complex and I must fully understand it ! Would anyone please be able to explain it to me ? Also, how would I change the program such that the parent and the child execute different computation?
Thanks a lot for your help with this :)
Upvotes: 0
Views: 206
Reputation: 3892
fork() creates a new process. So from that point on, there will be two separate processes that both continue from the point of code where the fork() was. In the main process fork() returns the PID of the new child process and in the child process it returns zero. So the code will execute different branches of the if statement in different processes.
Please also remember that new process is not the same thing as thread. Those processes won't have any global variables or similar things in common but they are completely separate. But they otherwise they are identical.
Upvotes: 4
Reputation: 5425
The fork()
function generates what is called a child process. The child process is a clone of the process that called fork()
in the first place. It even starts executing at the same place the parent process left off, which is right after calling fork()
.
The only difference is that fork()
will return true
(or zero) for the parent process and false
(or non-zero) for the child process. That means the parent process, after calling fork()
, will execute the first part of the conditional. The child process will start executing the second part of the conditional.
Each one will print 1000 times as they are scheduled by the operating system, and each will eventually terminate when they reach the end of the main method.
Upvotes: 1
Reputation: 272457
The fork()
function spawns a new process, with an exact copy of the memory of the original "parent" process. Both processes continue to execute from the same point, but fork()
returns 0 for the child, and non-zero for the parent. So the parent executes the first loop, and the child executes the second loop.
Note that as there is nothing synchronising the parent and the child, the order that you see the strings displayed on screen will be essentially random.
Upvotes: 1