【发布时间】:2016-06-02 03:19:19
【问题描述】:
在陈述我的问题之前,我已经阅读了几个关于堆栈溢出的相关问题,例如pipe & dup functions in UNIX 和其他几个问题,但没有澄清我的困惑。
首先是代码,这是来自“Beginning Linux Programming”第 4 版第 13 章的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
int data_processed;
int file_pipes[2];
const char some_data[] = "123";
pid_t fork_result;
if (pipe(file_pipes) == 0)
{
fork_result = fork();
if (fork_result == (pid_t)-1)
{
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
if (fork_result == (pid_t)0) // Child process
{
close(0);
dup(file_pipes[0]);
close(file_pipes[0]); // LINE A
close(file_pipes[1]); // LINE B
execlp("od", "od", "-c", (char *)0);
exit(EXIT_FAILURE);
}
else // parent process
{
close(file_pipes[0]); // LINE C
data_processed = write(file_pipes[1], some_data,
strlen(some_data));
close(file_pipes[1]); // LINE D
printf("%d - wrote %d bytes\n", (int)getpid(), data_processed);
}
}
exit(EXIT_SUCCESS);
}
执行结果为:
momo@xue5:~/TestCode/IPC_Pipe$ ./a.out
10187 - 写入 3 个字节
momo@xue5:~/TestCode/IPC_Pipe$ 0000000 1 2 3
0000003
momo@xue5:~/TestCode/IPC_Pipe$
如果你评论了LINE A、LINE C、LINE D,结果同上。 我理解结果,孩子通过连接到管道的自己的标准输入从其父母那里获取数据,并将“od -c”结果发送到它的标准输出。
但是,如果您评论了 LINE B,结果将是:
momo@xue5:~/TestCode/IPC_Pipe$ ./a.out
10436 - 写入 3 个字节
momo@xue5:~/TestCode/IPC_Pipe$
没有“od -c”结果! 由 execlp() 启动的“od -c”是否未执行,或者其输出未定向到标准输出?一种可能性是 'od' 的 read() 被阻止,因为如果您评论了 LINE B,则子级的写入文件描述符 file_pipes[1] 是打开的。但是评论 LINE D,这会让父级的写入文件描述符 file_pipes[1] 打开, 仍然可以有 'od -c' 输出。
还有,为什么我们需要在 execlp() 之前关闭管道? execlp() 将使用来自“od”的新图像替换进程图像,包括堆栈、.data、.heap、.text。这是否意味着,即使您没有将子文件中的 file_pipes[0] 和 file_pipes[1] 作为 LINE A 和 B 关闭,file_pipes[0] 和 file_pipes[1] 仍然会被 execlp()“破坏”?从代码的结果来看,它不是。但是我哪里错了?
非常感谢您在这里的时间和努力~~
【问题讨论】: