Information Technology Reference
In-Depth Information
intchild_pid=fork();
if(child_pid==0){ //I'mthechildprocess
//getpidisasystemcalltogetthecurrentprocess'sID
printf("Iamprocess#%d\n",getpid());
return0;
}else{
//I'mtheparent
printf("Iamparentofprocess#%d\n",child_pid);
return0;
}
Possibleoutput:
Iamparentofprocess495
Iamprocess495
Anotherlesslikelybutstillpossibleoutput:
Iamprocess456
Iamparentofprocess456
Figure3.5: Example UNIX code to fork a process, and some possible outputs
of running the code.
Initialize the address space with a copy of the entire contents of the address
space of the parent
Inherit the execution context of the parent (e.g., any open files)
Inform the scheduler that the new process is ready to run
A strange aspect of UNIX fork is that the system call returns twice: once
to the parent and once to the child. To the parent, UNIX returns the process
ID of the child; to the child, it returns 0 indicating success. Just as if you made
a clone of yourself, you would need some way to tell who was the clone and who
was the original, UNIX uses the return value from fork to distinguish the two
copies. Some sample code to call fork is given in Figure 3.5.
If we run the program in Figure 3.5, what happens? If you have access
to a UNIX system, you can try it and see for yourself. UNIX fork returns
twice, once in the child, with a return value of 0, and once in the parent with
a return value of the child's process ID. However, we do not know whether the
parent will run next or the child. The parent had been running, and so it is
likely that it will reach its print statement first. However, a timer interrupt
could intervene between when the parent forks the process and when it reaches
the print statement, so that the processor is reassigned to the child. Or we
could be running on a multicore, where both the parent and child are running
simultaneously. In either case, the child could print its output before the parent.
We will talk in much more depth about the implications of different orderings
of concurrent execution in the next chapter.
 
Search WWH ::




Custom Search