Peter
Peter

Reputation: 337

Unexpected pipe() behaviour

I'm trying to make 2 processes to communicate over a pipe. I wait for the child to write a character in the pipe, and after that, the parent would read the character from the pipe and display it on the screen. The problem is that I successfully write the character in the pipe (I did a test to read immediately from it, and I saw that it was in the pipe), but when the parent reads from the pipe, there is nothing inside of it. I don't really understand why; everything seems fine.

int PID, canal[2];
if(-1 == (PID = fork()))
{
    perror("Error");
    return 0;
}
if(-1 == pipe(canal))
{
    perror("Error");
    return 0;
}
if(PID == 0)
{
    close(canal[0]);
    printf("Child\n");
    char buffer = 'C';
    if( 0 == write(canal[1], &buffer, sizeof(char)))
        printf("Didn't write anything\n");
    close(canal[1]);
}
else
{
    char readBuffer;
    wait(NULL);
    printf("Parent\n");
    close(canal[1]);
    if(read(canal[0], &readBuffer, sizeof(char)))
    {
        printf("I read: ");
        printf("%c\n", readBuffer);
    }
    close(canal[0]);
}

Upvotes: 0

Views: 106

Answers (1)

Sam Hartman
Sam Hartman

Reputation: 6489

The issue is that you call pipe after you call fork. So the parent and child get different copies of the pipe. Move the call to pipe before your call to fork.

Upvotes: 5

Related Questions