HappyUser
HappyUser

Reputation: 309

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;

}

Upvotes: 0

Views: 3101

Answers (1)

ritlew
ritlew

Reputation: 1682

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].

Upvotes: 1

Related Questions