-
simple fork() program
folks,
I am trying to understand forking. I know fork() is multithreading or multitasking (from wikipedia). I have the following program that I am running using cygwin:
Code:
#include <stdio.h>
#include <stdlib.h>
void doit()
{
if (fork() == 0){
fork();
printf("hello\n");
exit(0);
}
return;
}
int main()
{
doit();
printf("hello\n");
exit(0);
}
When I run the above the output I get is the following:
hello
$ hello ----I am confused of this???
hello
is the $ hello above an output line? If it is an output line then does it print a total of 1 hello output line?
Thanks for your help.
-
The $ is your prompt. Follow this carefully. Your main thread is fork()ing. Then the child thread is fork()ing again. Thus two child threads are printing "hello\n" in your function, while your parent thread is printing "hello\n" in main(). When your parent program closes, the prompt is appearing, but your child processes may not have finished printing, yet, thus they keep printing after the parent returned.
In general, in computer land, parents are supposed to wait for the deaths of all of their children.
-
Thank you very much for clearing that up.
-
Making a call to fork() creates a new process by duplicating the calling process. It doesn't create a new thread (well, it does create a new thread, but indirectly, since a process always have at least one thread -- correct me if I'm wrong). So, fork() has more to do with multitasking than multithreading, like you would say.