c - 为什么等待后我不能关闭管道?
问题描述
我试图了解如何wait()
工作。ls -F -1 | nl
这是在命令行中模仿的ac程序
pipe(fd); // create the pipe
pid1 = fork(); //fork child 1
if (pid1 == 0) // child 1
{
close(fd[0]); // close read end of the pipe
dup2(fd[1], 1); // child 1 redirects stdout to write to the pipe
execlp("ls", "bin/ls", "-F", NULL); // execute ls -F
close(fd[1]); // close write end of the pipe
}
pid2 = fork(); //fork child 2
if (pid2 == 0) // child 2
{
close(fd[1]); // close write end of the pipe
dup2(fd[0], 0); // child 2 redirects stdin to read from the pipe
execlp("nl", "usr/bin", NULL); // execute nl
close(fd[0]); // close read end of the pipe
}
if (pid1 != 0 && pid2 != 0) // parent process
{
wait(NULL); // wait for a child
wait(NULL); // wait for another child
close(fd[0]); // close read end of parent pipe
close(fd[1]); // close write end of parent pipe
}
我最初认为的顺序wait(NULL)
并不close(fd)
重要。但显然确实如此。wait(NULL)
为什么这段代码在正常工作的情况下移动两个下面的代码时一直运行而不打印任何东西close(fd[1])
?
解决方案
nl
在 EOF on 之前不会退出stdin
。在父子 1 都关闭管道的写入端之前,这不会发生。子 1 在退出时会执行此操作,父级会在退出时执行此操作close(fd[1])
。
所以你陷入了僵局。在第二个返回之前您不会关闭 FD wait()
,但在您关闭 FD 之前它不会返回。
推荐阅读
- python - 如何在 Atoti 中动态过滤向量?
- json - 使用 Google 表格作为 JSON 端点的 Google 表格发布到 Web 问题
- python - 如何使方法 JSON 可序列化以在自定义 Pyspark 转换器中使用
- angular - 一个 svg 图片文件在 Palette 中渲染成功,但在 Angular 和 GoJS 中却没有
- mysql - 存储过程中查询不使用主索引,速度很慢
- c# - 如何更改 netstandard 2.0 库使用的 Newtonsoft.Json 的版本
- wmi - 设计电压参数是什么意思
- android - collectionGroup 查询可以选择父文档的所有内部文档吗
- ios - 如何在按钮按下时从数组数据中显示 iOS 表格视图 - Swift
- swift - 本地 Bundle.main 的 URL 总是返回 nil