【发布时间】:2017-04-15 14:30:35
【问题描述】:
程序执行,但未显示最终输出。我似乎弄乱了输出的管道。
删除了对 execlp()、pipe()、fork() 失败的检查,因为它们不会导致上述问题。
#include "iostream"
#include "stdlib.h"
#include "unistd.h"
#include "wait.h"
#include "stdio.h"
#include "fcntl.h"
using namespace std;
int main(int argc, char **argv)
{
int fd[2],status,status2,fd1[2];
pipe(fd);
pipe(fd1);
char buf[12];
switch(fork())
{
case 0:
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("ls","ls",NULL);
exit(0);
break;
default:
waitpid(-1,&status,0);
close(fd[1]);
close(fd1[0]);
dup2(fd1[1],1);
close(fd1[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("wc","wc",NULL);
}
switch(fork())
{
case 0:
close(fd1[1]);
dup2(fd1[0],0);
close(fd1[0]);
execlp("wc","wc",NULL); //this is not being redirected to STDOUT
exit(0);
break;
default:
waitforpid(-1,&status2,0);
}
return 0;
}
【问题讨论】: