When fork()被调用时,一个进程会生成一个具有共享或重复进程段的子进程。这意味着在程序中,之前fork()被调用时,只有一个进程,或者一个执行单元。后fork()返回,有两个进程同时运行。由于此时两个进程具有相同的调用堆栈,因此每个进程看起来就像刚刚调用过fork()。在父进程中,返回值是fork()是子进程的PID。在子进程中,返回值是fork() is 0.
您可以通过一个非常简单的演示来了解这一点:
#include <unistd.h>
#include <stdio.h>
int main(){
pid_t parent = getpid();
pid_t child = fork();
if(child != 0){
printf("I am the parent process. My PID is %d\n", parent);
printf("Parent process terminating\n");
}
else{
printf("I am the child process. My PID is %d\n", getpid());
printf(" My parent's PID is %d\n", parent);
printf("Child process terminating\n");
}
return 0;
}
这是在我的笔记本电脑上运行的示例:
$ gcc -o fork fork.c
$ ./fork
I am the parent process. My PID is 16048
Parent process terminating
I am the child process. My PID is 16049
My parent's PID is 16048
Child process terminating
$
$ ./fork
I am the parent process. My PID is 16265
Parent process terminating
$ I am the child process. My PID is 16266
My parent's PID is 16265
Child process terminating