【问题标题】:using fork twice - weird behavior使用 fork 两次 - 奇怪的行为
【发布时间】:2016-05-19 07:31:27
【问题描述】:

我正在尝试创建 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 条件中的分配周围添加括号。

标签: c linux pipe fork


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2018-01-01
    • 2020-09-03
    • 2016-04-30
    • 1970-01-01
    • 2019-12-09
    相关资源
    最近更新 更多