写入封闭管道之前进行 C 检查
有没有一种简单的方法可以在用 C 写入管道之前检查管道是否已关闭?我有一个子进程和父进程,父进程有一个管道可以写入子进程。但是,如果子级关闭管道并且父级尝试读取 - 我会收到损坏的管道错误。
那么我如何检查以确保我可以写入管道,以便在无法写入时可以将其作为错误处理?谢谢!
Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error.
So how can I check to make sure I can write to the pipe, so I can handle it as an error if I can't? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种简单的检查方法是对管道执行 0 字节 write(2) 并检查返回。如果您正在捕获 SIGPIPE 或检查 EPIPE,则会收到错误消息。但这与您继续进行实际写入并检查错误返回是一样的。因此,只需在信号处理程序 (SIGPIPE) 中进行写入并处理错误,或者如果信号被忽略,则通过检查写入返回的错误来处理错误。
A simple way to check would be to do a 0 byte write(2) to the pipe and check the return. If you're catching SIGPIPE or checking for EPIPE, you get the error. But that's just the same as if you go ahead and do your real write, checking for the error return. So, just do the write and handle an error either in a signal handler (SIGPIPE) or, if the signal is ignored, by checking the error return from write.
尝试编写并处理错误怎么样?与写入文件或数据库的方式相同。我认为这个习语没有任何价值:
你只是引入了一个更小、更难在测试中捕获的机会窗口:
How about just try to write and deal with the error? The same way you would for a write to a file or a database. I see no value in the idiom:
You merely introduce a smaller, and harder to catch in testing, window of opportunity: