可重入函数 read()

发布于 2024-10-31 11:13:14 字数 280 浏览 1 评论 0原文

我通过 select() 找到了一个服务器,我想从一些客户端接收该服务器。

但我发现服务器会被gdb阻塞在read()中。

所以我想到通过添加一个SIGALRM来解决它,但是 当发生超时时,它仍然被阻塞在read()中。

发生这种情况是因为系统调用会自动重新启动,read() 当 SIGALRM 信号处理程序返回时,不会被中断。

这个解释正确吗?

I have found a server by select(), which I want to receive from some clients.

But I find that the server will get blocked in read() by gdb.

So I thought of solving it by adding a SIGALRM, but
when a timeout occurs, it's still blocked in read().

This happens because, system calls are automatically restarted, the read()
is not interrupted when the SIGALRM signal handler returns.

Is this interpretation correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

余厌 2024-11-07 11:13:14

此问题的通常解决方案是使用 SOCK_NONBLOCKsocket(2)O_NONBLOCKfcntl(2)F_SETFL 命令。一旦套接字被标记为非阻塞,当您尝试从中读取数据时,它就永远不会阻塞,并且您无需尝试跨越阻塞与非阻塞之间的界限。您确定 select(2) 设置了文件描述符吗? select(2) 联机帮助页确实描述了您看到所看到内容的原因之一,但似乎不太可能:

在 Linux 下,select() 可能会将套接字文件描述符报告为
“准备阅读”,而随后的阅读
块。例如,当数据到达时,可能会发生这种情况
但经检查有错误的校验和并被丢弃。
可能还有其他情况需要文件描述符
虚假地报告为准备就绪。因此使用起来可能更安全
O_NONBLOCK 不应阻塞的套接字。

如果您确实只是想阻止自动重新启动,请查看 sigaction(2) 中的 SA_RESTART 以阻止可重新启动的系统调用重新启动。

The usual solution to this problem is to use SOCK_NONBLOCK to socket(2) or O_NONBLOCK to fcntl(2)'s F_SETFL command. Once the socket is marked non-blocking, it'll never block when you try to read from it, and you won't need to try to straddle the divide between blocking or non-blocking. Are you sure select(2) set the filedescriptor? The select(2) manpage does describe one reason why you see what you're seeing, but it doesn't seem likely:

Under Linux, select() may report a socket file descriptor as
"ready for reading", while nevertheless a subsequent read
blocks. This could for example happen when data has arrived
but upon examination has wrong checksum and is discarded.
There may be other circumstances in which a file descriptor is
spuriously reported as ready. Thus it may be safer to use
O_NONBLOCK on sockets that should not block.

If you really just want to prevent the automatic restart, look into SA_RESTART in sigaction(2) to prevent restartable system calls from restarting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文