Linux:在不执行read()/write()的情况下检查套接字/管道是否损坏 [英] Linux: Checking if a socket/pipe is broken without doing a read()/write()

查看:98
本文介绍了Linux:在不执行read()/write()的情况下检查套接字/管道是否损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段简单的代码,它定期将数据写入传递给它的fd中. fd很可能是管道或插座,但可能是任何东西.每当我对套接字/管道进行write()时,我都可以检测到套接字/管道何时关闭/断开,因为我遇到了EPIPE错误(我忽略了SIGPIPE).但是我不会一直写它,因此可能很长一段时间都无法检测到关闭的套接字.我需要对关闭尽快做出反应.是否有一种无需执行write()即可检查fd的方法?如果我什么都没写,那么我可以定期执行此操作.

I have a simple piece of code that periodically writes data to a fd that's passed to it. The fd will most likely be a pipe or socket but could potentially be anything. I can detect when the socket/pipe is closed/broken whenever I write() to it, since I get an EPIPE error (I'm ignoring SIGPIPE). But I don't write to it all the time, and so might not detect a closed socket for a long time. I need to react to the closure asap. Is there a method of checking the fd without having to do a write()? I could then do this periodically if I'm not writing anything.

推荐答案

struct pollfd pfd = {.fd = yourfd, .events = POLLERR};
if (poll(&pfd, 1, whatever) < 0) abort();
if (pfd.revents & POLLERR) printf("pipe is broken\n");

这确实对我有用.请注意,套接字并不完全是管道,因此表现出不同的行为(->使用POLLRDHUP).

This does work for me. Note that sockets are not exactly pipes and thus show different behavior (-> use POLLRDHUP).

这篇关于Linux:在不执行read()/write()的情况下检查套接字/管道是否损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆