gpt4 book ai didi

c - 使用 fork 两次 - 奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:35 25 4
gpt4 key购买 nike

我正在尝试创建 2 个子进程并将它们与管道连接,但我的代码出了点问题。

int des_p[2];
if(pipe(des_p) == -1) {
perror("Pipe failed");
exit(1);
}
if((this->procId = fork())==0){ //filter for only the SON process to pass
close(STDOUT_FILENO); //closing stdout
dup(des_p[1]); //replacing stdout with pipe write
close(des_p[0]); //closing pipe read
close(des_p[1]); //closing pipe write

execvp(op1, argsp1);
perror("execvp failed");
exit(1);
}
if(this->procIdSecondary = fork() == 0) //creating 2nd child, also a filter for only the SON process to pass
{
close(STDIN_FILENO); //closing stdin
dup(des_p[0]); //replacing stdin with pipe read
close(des_p[1]); //closing pipe write
close(des_p[0]); //closing pipe read

execvp(op2, argsp2);
perror("execvp failed");
exit(1);
}
else
{
cout <<"pid=" << this->procIdSecondary<<endl;

}

close(des_p[0]);
close(des_p[1]);

`

我得到 pid=0

这怎么可能?

最佳答案

您的问题是此 if 语句中的运算符优先级

if(this->procIdSecondary = fork() == 0)

this->procIdSecondary 被分配比较的结果。在第一个 if 中添加括号。

关于c - 使用 fork 两次 - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37316680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com