Search code examples
cpipeposix

Detecting pipe hangup


How can I get to know, in the reader process, if the write end of pipe is still active (writer process didn't close its descriptor or exit). I mean Posix (C language) interface. As it seems, if the reader process has is descriptor NONBLOCK, it cannot be guessed by the effect of "read" call. I tried checking the desciptor flags but they don't change:

Writer:

#include <unistd.h>

int main() {
    sleep(2);
    //actually doesn't write anything but has
    //stdout open and exits before reader does
}

Reader:

#include <fcntl.h>
#include <cstdio>
#include <unistd.h>


int main() {
    
    int i = fcntl(0, F_GETFL);
    int j = fcntl(0, F_GETFD);
    //now the write end is alive
    printf("i: %d, j: %d\n", i, j);
    sleep(3);
    i = fcntl(0, F_GETFL);
    j = fcntl(0, F_GETFD);
    //now the write end has exited
    printf("i: %d, j: %d\n", i, j);
    //all flags are all the time 0
}

Supposing that these programs were connected into a pipeline (using "pipe" call) by some external program.


Solution

  • read will return 0 once the write end of the pipe is closed and all pending data is read. If there is no data and the pipe is not closed and non-blocking mode is enabled read will return -1 and set errno to EAGAIN.

    When the write end is closed poll will return a POLLHUP event for the pipe.