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!");

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: */

/* 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:

Unique to the child:

[an error occurred while processing this directive]