Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There are tons of questions about non blocking pipes, but there are NO examples of code that can be copy&paste (with little correction) and used.

I got the idea and sources from this thread: Non-blocking pipe using popen?

But how to use it? At while cycle? Please, review my changes. Is it really need to use errno == EAGAIN & additional header #include <cerrno> ? Suggest you own better version if need:

    FILE *pipe;
    char buff[512];
    if ( !(pipe = popen( command.c_str(), "r")) ) return false;

    int d = fileno(pipe);   
    while ( true )
    {
        ssize_t r = read(d, buff, sizeof(buff));
        if (r == -1 && errno == EAGAIN) // really need errno? 
            continue;
        else if (r > 0)
            ptr_output->append(buff);       
        else
            break;
    }

    pclose(pipe);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
476 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes. If the read call returns with the error value (-1) and errno is set to EAGAIN, that means that no data is available, so you continue the loop to try again. If you got rid of the errno, errors would be effectively ignored, and your program would probably crash. Imagine if you did remove it: When read returned -1, but, say, the error was that the pipe was broken (the other end closed it), you would just keep trying to loop and enter an infinite loop. Bad idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...