Question

I've written the following code:

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFF 200


int main(int argc, char *argv[]) {

    char write_buffer[BUFF];
    char read_buffer[BUFF];

    strcpy(write_buffer, "This string supposed to be sent from parent to child");

    int fds[2];
    pid_t pid;

    if ((pid=fork())==-1) {
        perror("fork error");
    }

    if (pipe(fds)==-1) {
        perror("pipe error");
    }


    else if (pid==0) { // child


        int bytes;
        if ((bytes=read(fds[0], read_buffer, BUFF))==-1) {
            perror("read error");
        }
        else {
            printf("read %d bytes from pipe\n", bytes);
        }
    }

    else { // parent

        if (write(fds[1], write_buffer, strlen(write_buffer))==-1) {
            perror("write error");
        }

        printf("FLAG to check if write() went through\n"); // this will print!

        wait(NULL);
    }
}

The simple code above is an attempt to send data through a pipe, from a parent process to a child process.
Problem is, the execution is suspended for some reason...
The child process blocked at the read() system call (or at least it seems to be), and the parent just sits there, waiting for it to finish, but that never happens.
What is the problem here? clearly, the parent process has enough time to write write_buffer to the pipe, so the child process won't call read() on an empty pipe.

Was it helpful?

Solution

You fork and then you create the pipe so each process is going to its own set of pipes that don't talk to each other.

Just switch the code around and call pipe before fork and you should be good to go.

Also, though it probably won't matter here, get in the habit of reading and writing in a loop. read & write are not guaranteed to get nor put all the data you request in one call. Likewise, close your pipes after you done. Closing the write end of the pipe will signal to the reader that the end-of-file has been reached.

while (read(fds[0], read_buffer, sizeof(read_buffer)) > 0) 
{
    //process bytes read
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top