Article Title: about the use of Linux operating system Fork. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Fork creates a new process. The newly created process is a sub-process. It is a copy of the code of the parent process and is usually used on the server where multiple processes are processed, you can also run independent code in a sub-process.
You can use getpid to determine whether the current process is a child process or a parent process.
Let's look at the example below:
#include
#include
#include
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 using gcc in linux. The running result is as follows:
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] |