Penguin

NAME

fork - create a child process

SYNOPSIS

#include <sys/types.h> /* for pid_t / #include <unistd.h> / for fork(2) prototype */ pid_t fork(void);

DESCRIPTION

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.

RETURN VALUE

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.

ERRORS

EAGAIN
fork(2) cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child, or the number of processors would exceed the limit of the number of processes either system wide, or for a particular users. (CHILD_MAX)
Note: The Linux kernel appears to only return this error if the fork(2) would exceed the maximum allowed number of processes from one limit or another.
ENOMEM
fork(2) failed to allocate the necessary kernel structures because memory is tight.

CONFORMING TO

The fork(2) call conforms to SVr4, SVID, POSIX, X/OPEN, BSD 4.3.

EXAMPLE

/*

  • This program demonstrates fork(2).
  • /
  1. include <sys/types.h> /* for pid_t */
  2. include <unistd.h> /* for fork(2) */
  3. include <stdio.h> /* for printf(3), fprintf(3) */
  4. include <string.h> /* for strerror(3) */
  5. include <errno.h> /* for errno */

int main(int argc,char **argv) {

pid_t pid;

pid = fork();

if (pid == -1) {

fprintf(

stderr, "fork(): %s (%i)\n", strerror(errno), errno);

return 1;

}

if (pid == 0) {

printf("I am the child!\n");

for(;;) {

printf("a"); fflush(stdout);

}

} else {

printf("I am the parent! The child's PID is %i\n",pid);

for(;;) {

printf("b"); /* Delete previous char */ fflush(stdout);

}

} return 0;

}

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.

SEE ALSO

clone(2), execve(2), vfork(2), wait(2)

This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.