多个 fork 语句
Multiple Fork Statements
此代码在原始进程之外创建了 3 个进程。因此总共存在 4 个进程。据我所知,这段代码应该打印 8 条语句。然而,结果只有 4 个语句。
我在这里错过了什么?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
// error checking is omitted
int main(int argc, char const *argv[])
{
pid_t pid, pid2;
fflush(stdout);// used to clear buffers before forking
pid = fork();
fflush(stdout);
pid2 = fork();
if(pid == 0) {
printf("%d is the first generation child from first fork\n", getpid());
}
else if(pid > 0) {
printf("%d is the original process\n", getpid());
wait();
}
else if(pid2 == 0) {
printf("%d is the 2nd generation child from the second fork by the first generation child \n", getpid());
}
else if(pid2 > 0) {
printf("%d is the first generation younger child from the 2nd fork by the original\n", getpid() );
wait();
}
return 0;
}
输出
4014为原进程
4016是原始进程
4015 是第一个 fork 的第一代 child
4017 是来自第一个 fork
的第一代 child
因为else if,每个进程只能打印一行,4个进程就是4行。
你应该替换:
else if(pid2 == 0) {
作者:
if(pid2 == 0) {
必须对 pid 和 pid2 进行测试才能为每个进程打印 2 行。
此代码在原始进程之外创建了 3 个进程。因此总共存在 4 个进程。据我所知,这段代码应该打印 8 条语句。然而,结果只有 4 个语句。 我在这里错过了什么?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
// error checking is omitted
int main(int argc, char const *argv[])
{
pid_t pid, pid2;
fflush(stdout);// used to clear buffers before forking
pid = fork();
fflush(stdout);
pid2 = fork();
if(pid == 0) {
printf("%d is the first generation child from first fork\n", getpid());
}
else if(pid > 0) {
printf("%d is the original process\n", getpid());
wait();
}
else if(pid2 == 0) {
printf("%d is the 2nd generation child from the second fork by the first generation child \n", getpid());
}
else if(pid2 > 0) {
printf("%d is the first generation younger child from the 2nd fork by the original\n", getpid() );
wait();
}
return 0;
}
输出
4014为原进程 4016是原始进程 4015 是第一个 fork 的第一代 child 4017 是来自第一个 fork
的第一代 child因为else if,每个进程只能打印一行,4个进程就是4行。
你应该替换:
else if(pid2 == 0) {
作者:
if(pid2 == 0) {
必须对 pid 和 pid2 进行测试才能为每个进程打印 2 行。