C

时间:2018-06-25 17:44:26

标签: c linux pipe file-descriptor

我在c中有一个基本管道,我向子进程发送了一个整数,子进程将此数字加1,然后将其发送回父进程。 我的问题是:如果在写函数之后立即关闭写文件描述符,会发生什么情况?程序将显示1(正确的输出为2

int main(){

    int p[2];

    pipe(p);

    int n=1;
    write(p[1], &n, sizeof(int));
    close(p[1]); // don't work => the output is 1

    if(fork() == 0) {
            read(p[0], &n, sizeof(int));
            n = n + 1;
            write(p[1], &n, sizeof(int));
            close(p[1]);
            close(p[0]);
            exit(0);
    }
    wait(0);
    read(p[0], &n, sizeof(int));
    close(p[0]);
    //close(p[1]);  works => the output is 2

    printf("%d\n", n);
    return 1;

}

1 个答案:

答案 0 :(得分:1)

正确的输出肯定不是2。当您在分叉之前关闭管道时,两个过程现在都如何关闭pipe[1]。当子进程尝试写入管道时,它将无法写入。因此,父级将读取1,因为从未将2写入pipe[1]

相关问题