fork - create a child process
#include <sys/types.h> /* for pid_t / #include <unistd.h> / for fork(2) prototype */ pid_t fork(void);
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.
The fork(2) call conforms to SVr4, SVID, POSIX, X/OPEN, BSD 4.3.
/*
- This program demonstrates fork(2).
- /
- include <sys/types.h> /* for pid_t */
- include <unistd.h> /* for fork(2) */
- include <stdio.h> /* for printf(3), fprintf(3) */
- include <string.h> /* for strerror(3) */
- 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.
50 pages link to fork(2):