使用fork两次 - 奇怪的行为

时间:2016-05-19 07:31:28

标签: c linux pipe fork

我试图创建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

怎么可能?

1 个答案:

答案 0 :(得分:0)

您的问题是此if声明

中的运算符优先级
if(this->procIdSecondary = fork() == 0)

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