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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…