Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

c++ - Correct Code - Non-blocking pipe with popen

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...