我不确定以下操作是否可行,因为我在Google上找不到任何相关问题或结果。我想要将fork()的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);
}
}
你好世界
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
的错误消息。 - William Pursell