Fork creates a new process. The newly created process is a child process. It is a copy of the subsequent code of the parent process. It is usually used as a multi-process server. It can also run independent code in the child process.
Use getpid to determine whether the current process is a child process or a parent process.
Consider the following example:
The following is the quoted content:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { pid_t pid; static int n = 0; printf("fork!n"); switch (pid = fork()) { case-1: { /* ..pid.-1.fork.... */ /* ....... */ /*..........*/ perror("The fork failed!"); break; } case 0: { /* pid.0.... */ printf("[child]i am child!n"); printf("[child]getpid=[%d]n", getpid() ); printf("[child]pid=[%d]n", pid ); break; } default: { /* pid..0.... */ printf("[parent]i am parent!n" ); printf("[parent]getpid=[%d]n",getpid() ); printf("[parent]pid=[%d]n",pid ); break; } } printf("n=[%d]n", n++); return 0; } |
This example is compiled with gcc under Linux, and the running results are as follows:
The following is the quoted content:
fork! [child]i am child! [child]getpid=[7422] [child]pid=[0] n=[0] [parent]i am parent! [parent]getpid=[7421] [parent]pid=[7422] n=[0] |