0
我想fork和exec,父進程在stdout/stderr上處理任何東西。 不幸的是父進程沒有得到任何輸出。也就是說,讀取的調用總是返回一個非正整數。POSIX:捕獲子進程輸出
這是代碼。怎麼了?
#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;
}
}
}
當刪除這兩個行:
fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL) | O_NONBLOCK);
fcntl(err[0], F_SETFL, fcntl(err[0], F_GETFL) | O_NONBLOCK);
一切正常。我想要非阻塞IO,但...
感謝您閱讀我的文章。
看起來像這樣的問題:http://stackoverflow.com/questions/7292642/grabbing-output-from-exec/7292659 – Aif
不完全。至少它不會幫助這個代碼:( – user986331