Search code examples
cpipefork

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;
}

Solution

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