fork - create a child process
fork(2) creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.
Under Linux, and in fact any modern implementation of Unix, fork(2) is implemented using copy-on-write pages, so the only penalty incurred by fork is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
- include <errno.h> /* for errno */
pid = fork();
printf("I am the child!\n");
printf("I am the parent! The child's PID is %i\n",pid);
Note that on a machine with a single CPU, this will output large groups of "aaaaa...." followed by large groups of "bbbb..." as each process gets a timeslice. On a machine with more than one CPU, you might be more likely to see "a" and "b" interspersed in smaller units as both processes can run at the same time.