我不确定是否可以完成以下任务,因为我无法通过Google找到任何问题/结果。我想将fork()的stdout更改为管道,然后将其更改回正常的stdout。Unix C - 将stdout重定向到pipe然后返回stdout
这是我有:
FirstExecutable:
int main()
{
int fd[2]; //Used for pipe
int processID;
if(pipe(fd) == -1)
{
printf("Error - Pipe error.\n");
exit(EXIT_FAILURE);
}
if((processID = fork()) == -1)
{
fprintf(stderr, "fork failure");
exit(EXIT_FAILURE);
}
if(processID == 0)
{
int newFD = dup(STDOUT_FILENO);
char newFileDescriptor[2];
sprintf(newFileDescriptor, "%d", newFD);
dup2 (fd[1], STDOUT_FILENO);
close(fd[0]);
execl("./helloworld", "helloworld", newFileDescriptor, NULL);
}
else
{
close(fd[1]);
char c[10];
int r = read(fd[0],c, sizeof(char) * 10);
if(r > 0)
printf("PIPE INPUT = %s", c);
}
}
的HelloWorld
int main(int argc, char **argv)
{
int oldFD = atoi(argv[1]);
printf("hello\n"); //This should go to pipe
dup2(oldFD, STDOUT_FILENO);
printf("world\n"); //This should go to stdout
}
所需的输出:
world
PIPE OUTPUT = hello
实际输出:
hello
world
'man perror'不要使用'fprintf'打印错误信息而不用'strerror' – 2013-02-25 06:33:53
感谢您的提示! – MrHappyAsthma 2013-02-25 07:56:00