【发布时间】:2019-04-05 15:56:20
【问题描述】:
我有两个子进程,它们共享父进程的公共管道描述符。关闭端等没有问题。问题是我希望将管道的读取端重定向到文件描述符,而不是保存缓冲区并将缓冲区的内容写入文件。是否可以?我的代码 sn-p 如下
// we're sure we can read from fd[0], I did it sucessfully
// I mean there is no problem about the communication
int open_fd = open(filename, O_WRONLY|O_CREAT, 0666);
if (dup2(open_fd,fd[0]) == -1) {
perror("error ");
return 1;
}
if (close(open_fd) == -1) {
perror("close error");
return 1;
}
当我执行上述代码时,我没有写入名为filename 的文件。顺便问一下,有没有必要通过调用close(open_fd)来关闭open_fd?由于dup2 已经关闭它。
【问题讨论】:
-
通常情况下,您会使用
dup2(a,b); close(a)。做dup2(a,b); close(b)真的没有任何意义。 -
@WilliamPursell 谢谢先生,我编辑了它。那么,现在的问题是什么?我该怎么办?
-
您不能通过复制文件描述符来神奇地将管道更改为文件。
-
@IanAbbott 那么我应该分别持有一个缓冲区、读入缓冲区、打开文件进行写入和写入文件吗?或者我该怎么办?
-
@concurrencyboy 这取决于。为什么首先需要创建管道?
标签: c pipe io-redirection dup2