简体   繁体   中英

File descriptors and pipe in C

I have a basic pipe in c, I have sent an integer to child process, the child process increase this number with 1 and will send back to parent process. My question is: What is happening if I close the write file descriptor right after write function ? The program will displayed 1 (the correct output is 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;

}

The correct output is certainly not 2 . When you close the pipe before forking, both processes now how a closed pipe[1] . When the child process attempts to write to the pipe, it will not be able to. Thus, the parent will read 1 , because 2 was never written to pipe[1] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM