A.J. Steinhauser
A.J. Steinhauser

Reputation: 40

Why does using read on a pipe hang when sending integers?

For the life of me I cannot figure out why this code is hanging. It everything executes up until read(pipe[1], &recieve, sizeof(int)); on the parent process.

#include <time.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

pid_t fork(void);

int main(){
    pid_t main_pid = getpid();
    int fd[2];
    pid_t newproc = fork();
    pipe(fd);
    if (getpid() != main_pid){
        int send = 5;
        write(fd[1], &send, sizeof(int));
    }
    else{
        while (wait(NULL) > 0);
        int recieve;
        read(fd[0], &recieve, sizeof(int));
        printf("%d\n",recieve);
    }
    return 0;
}

Upvotes: 0

Views: 141

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12668

You write

    pid_t newproc = fork();
    pipe(fd);

If you do the pipe() call after the fork() you end having two completely different pipes on parent and child (and unrelated to each other). The pipe call must be done before the fork, so both processes refer to the same pipe. In the way it is written above, neither the parent has access to the two descriptors the child has acquired, nor the child has access to the parent's.

Upvotes: 1

ikegami
ikegami

Reputation: 385655

You create two pipes.

The child writes to the pipe it created.

The parent reads from the completely unrelated pipe it created.

Since nothing was ever written the parent's pipe, reading from it blocks.

Swap the order of fork and pipe.

Upvotes: 1

Related Questions