Search code examples
clinuxunixpipeipc

how to establish a non blocking read from unix pipes?


Let‘s assume we have a pipe int InPipe[2];. How can you read the input until the pipe is empty without blocking when the whole available Data input was read?

I know this question has been asked several times, but I couldn’t assemble a suitable function.

This is my Code so far:

int InPipe[2];
char buffer[1024];
int rc;
while (true){
    read(InPipe[0], buffer, sizeof(buffer));
    fprintf(stdout, “%s“, buffer);
    bzero(&buffer, sizeof(buffer)); // Clearing Buffer
} 

Any Ideas, Suggestions, Code Snippets


Solution

  • Reading from a pipe

    Attempts to read from a pipe that is currently empty block until at least one byte has been written to the pipe. If the write end of a pipe is closed, then a process reading from the pipe will see end-of-file (i.e., read() returns 0) once it has read all remaining data in the pipe.

    taken from linux interface programming.

    You cant! the process reading from the pipe will be blocked in this situation.

    Due to people comments, i am adding this section:

    we can use a pipe to allow communication between two processes. To con-nect two processes using a pipe, we follow the pipe() call with a call to fork(). immediately after the fork(), one process closes its descriptor for the write end of the pipe, and the other closes its descriptor for the read end. For example, if the parent is to send data to the child, then it would close its read descriptor for the pipe, filedes[0], while the child would close its write descriptor for the pipe, filedes[1], then the code for this will be:

    int filedes[2];    
    
    if (pipe(filedes) == -1)   /* Create the pipe */        
        errExit("pipe");    
    
    switch (fork())        /* Create a child process */
    {                              
    case -1:        
        errExit("fork");    
    case 0:             /* Child */       
        if (close(filedes[1]) == -1)            /* Close unused write end */            
            errExit("close");        
    
        /* Child now reads from pipe */        
        break;    
    
    default: /* Parent */        
        if (close(filedes[0]) == -1)            /* Close unused read end */            
            errExit("close");        
        
        /* Parent now writes to pipe */        
        break;    
    }