我想在 C 程序中启动两个子进程。我使用了fork()两次,但是在检查pids 时,它看起来好像启动了四个进程:
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
int main(int argc, char *argv[]) {
pid_t one = fork();
pid_t two = fork();
if (one == 0) {
printf("child pid = %d\n", getpid());
}
if (two == 0) {
printf("child pid = %d\n", getpid());
}
if (one != 0 && two != 0) {
wait(NULL);
printf("parent pid = %d\n", getpid());
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
g@x:dir$ ./twochilds
child pid = 11408
child pid = 11407
child pid = 11409
child pid = 11409
parent pid = 11406
Run Code Online (Sandbox Code Playgroud)
fork()复制进程,它在父进程中的返回值是实际的子进程 pid,在子地址空间中为 0。假设所有调用都fork()成功,让我们看看发生了什么。
pid_t one = fork();
(created by parent) (created by child_1)
Parent --- Child_1 --- Child_2 --- Child_3
| one > 0 | one = 0 |
pid_t two = fork();
| one > 0 | one = 0 | one > 0 | one = 0
| two > 0 | two > 0 | two = 0 | two = 0
if (one == 0) { (Will be executed by child_1 and child_3)
printf("child pid = %d\n", getpid());
}
if (two == 0) { (Will be executed by child_2 and child_3
printf("child pid = %d\n", getpid());
}
if (one != 0 && two != 0) { (Will be executed by parent only)
wait(NULL);
printf("parent pid = %d\n", getpid());
}
Run Code Online (Sandbox Code Playgroud)
这就是为什么你打印了 5 行。
如果您只需要 2 个子进程,则可以执行以下操作:
pid_t pid = fork();
if (pid == -1) {
// handle error
} else if (pid == 0) {
// son process 1
} else {
pid = fork();
if (pid == -1) {
// handle error
} else if (pid == 0) {
// son process 2
} else {
// initial parent process
}
}
Run Code Online (Sandbox Code Playgroud)