C 多个Fork语句
此代码在原始进程的基础上创建了3个进程。因此,总共存在4个过程。据我所知,这段代码应该打印8条语句。然而,结果只有4条语句。 我错过了什么C 多个Fork语句,c,fork,C,Fork,此代码在原始进程的基础上创建了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; f
#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;
}
#包括
#包括
#包括
//省略错误检查
int main(int argc,char const*argv[]
{
pid_t pid,pid 2;
fflush(stdout);//用于在分叉之前清除缓冲区
pid=fork();
fflush(stdout);
pid2=fork();
如果(pid==0){
printf(“%d是第一个fork的第一代子代\n”,getpid());
}
否则,如果(pid>0){
printf(“%d”是原始进程\n“,getpid());
等待();
}
else if(pid2==0){
printf(“%d是第一代子对象从第二个fork生成的第二代子对象,\n”,getpid());
}
否则如果(pid2>0){
printf(“%d是原始版本的第二个fork的第一代较年轻的子代”\n“,getpid());
等待();
}
返回0;
}
输出
4014是原始流程
4016是原始流程
4015是第一代福克斯的第一代孩子
4017是第一个fork的第一代子代这是因为else if,每个进程只能打印一行,4个进程意味着4行 您应该替换:
else if(pid2 == 0) {
作者:
必须对pid和pid2进行两次测试,以便每个进程打印2行。如果有四个进程,为什么需要八条打印语句?这不是真正的“fork”问题-pid2==0测试基本上是不可访问的(除非第一个fork失败)@OliverCharlesworth我想对两个pid进行测试。我的问题是,由于复制粘贴,我为pid2添加了
else if
。@greggo是的。复制粘贴让我错过了额外的东西。我不知道我是怎么错过的。。。谢谢
if(pid2 == 0) {