我有 pthread 正在运行并等待来自套接字的消息。线程被阻塞等待消息,并且在收到新消息之前不会唤醒。有没有办法发送信号到线程唤醒和接收函数( recvmsg )返回与信号有关的错误代码?
答案 0 :(得分:3)
是的,默认情况下,SIGINT会中断所有系统调用。来自man recv
:
EINTR The receive was interrupted by delivery of a signal before any
data were available; see signal(7).
and
MSG_WAITALL (since Linux 2.2)
This flag requests that the operation block until the full request is
satisfied. However, the call may still return less data than requested
if a signal is caught, an error or disconnect occurs, or the next
data to be received is of a different type than that returned.
但是,您无法定位特定线程或特定操作。
如果您希望拥有此功能,我建议使用接收线程可以明确监听的条件。在Linux上有一个众所周知的技巧,允许接收线程同时使用select
或poll
监听以获取套接字和'条件' [1]。
诀窍是打开从主线程到客户端(接收)线程的管道。主机在达到某种状态时写入管道(信号可以这么说)。客户端(接收)线程可以简单地轮询管道和套接字,只检查两者中的哪一个唤醒它。
[1] 通常pthread_cond_wait
和poll
/ select
在没有比赛的情况下无法合并,因此您需要编写具有较小超时的等待循环。相比之下,在Win32上它就像WaitForMultipleObjects
一样简单,你就完成了