I am trying to fork and exec, with the parent process processing anything on stdout/stderr. Unfortuantely the parent process does not get any output. That is, the calls to read always return a non-positive integer.
Here's the code. Whats wrong?
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <string>
int main()
{
int out[2],err[2],in[2];
pipe(out);
pipe(err);
pipe(in);
int fork;
if(!(fork=::fork()))
{
dup2(in[0],STDIN_FILENO);
dup2(out[1],STDOUT_FILENO);
dup2(err[1],STDERR_FILENO);
execlp("/bin/ls","/bin/ls","-la","/");
}
fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL) | O_NONBLOCK);
fcntl(err[0], F_SETFL, fcntl(err[0], F_GETFL) | O_NONBLOCK);
for(;;)
{
int result;
waitpid(fork,&result,WNOHANG);
char ac[256];
int cnt;
while((cnt=read(out[0], ac, 256))>0)
{
std::cout << std::string(ac,ac+cnt) << std::flush;
}
while((cnt=read(err[0], ac, 256))>0)
{
std::cout << std::string(ac,ac+cnt) << std::flush;
}
if(WIFEXITED(result))
{
return 0;
}
}
}
When removing these two lines:
fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL) | O_NONBLOCK);
fcntl(err[0], F_SETFL, fcntl(err[0], F_GETFL) | O_NONBLOCK);
everything works as expected. I want non-blocking IO, though...
Thanks for reading my post.