Non-blocking pipe using popen?

后端 未结 3 1629
清歌不尽
清歌不尽 2020-12-04 20:16

I\'d like to open a pipe using popen() and have non-blocking \'read\' access to it.

How can I achieve this?

(The examples I found were all blocking/synchrono

3条回答
  •  我在风中等你
    2020-12-04 20:59

    Setup like this:

    FILE *f = popen("./output", "r");
    int d = fileno(f);
    fcntl(d, F_SETFL, O_NONBLOCK);
    

    Now you can read:

    ssize_t r = read(d, buf, count);
    if (r == -1 && errno == EAGAIN)
        no data yet
    else if (r > 0)
        received data
    else
        pipe closed
    

    When you're done, cleanup:

    pclose(f);
    

提交回复
热议问题