What does fork() do?

What does fork() do?



#include <sys/types.h>
#include <unistd.h>

pid_t fork(void);



The fork() function is used to create a new process from an
existing process. The new process is called the child process, and the
existing process is called the parent. You can tell which is which by
checking the return value from fork(). The parent gets the
child's pid returned to him, but the child gets 0 returned to him. Thus
this simple code illustrate's the basics of it.




pid_t pid;

switch (pid = fork())
{
case -1:
/* Here pid is -1, the fork failed */
/* Some possible reasons are that you're */
/* out of process slots or virtual memory */
perror("The fork failed!");
break;

case 0:
/* pid of zero is the child */
/* Here we're the child...what should we do? */
/* ... */
/* but after doing it, we should do something like: */
_exit(0);

default:
/* pid greater than zero is parent getting the child's pid */
printf("Child's pid is %d\n",pid);
}



Of course, one can use if()... else... instead of
switch(), but the above form is a useful idiom.



Of help when doing this is knowing just what is and is not inherited by
the child. This list can vary depending on Unix implementation, so take
it with a grain of salt. Note that the child gets copies of these
things, not the real thing.



Inherited by the child from the parent:






  • process credentials (real/effective/saved UIDs and GIDs)



  • environment



  • stack



  • memory



  • open file descriptors (note that the underlying file positions are
    shared between the parent and child, which can be confusing)



  • close-on-exec flags



  • signal handling settings



  • nice value



  • scheduler class



  • process group ID



  • session ID



  • current working directory



  • root directory



  • file mode creation mask (umask)



  • resource limits



  • controlling terminal



Unique to the child:






  • process ID



  • different parent process ID



  • Own copy of file descriptors and directory streams.



  • process, text, data and other memory locks are NOT inherited.



  • process times, in the tms struct



  • resource utilizations are set to 0



  • pending signals initialized to the empty set



  • timers created by timer_create not inherited



  • asynchronous input or output operations not inherited






Home FAQ