写入封闭管道之前进行 C 检查

发布于 2024-08-31 09:55:52 字数 151 浏览 2 评论 0原文

有没有一种简单的方法可以在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

套路撩心 2024-09-07 09:55:52

一种简单的检查方法是对管道执行 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.

白云不回头 2024-09-07 09:55:52

尝试编写并处理错误怎么样?与写入文件或数据库的方式相同。我认为这个习语没有任何价值:

check if *this* is going to work
do *this*

你只是引入了一个更小、更难在测试中捕获的机会窗口:

check if *this* is going to work
   child thinks "Ha, fooled you, I'm off now!"
do *this*, which now fails!

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:

check if *this* is going to work
do *this*

You merely introduce a smaller, and harder to catch in testing, window of opportunity:

check if *this* is going to work
   child thinks "Ha, fooled you, I'm off now!"
do *this*, which now fails!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文