更新时间:2021-08-11 05:28:32
SIGUSR1
信号没有到达您认为的位置.
The SIGUSR1
signal isn't going where you think it is.
在多线程程序中,raise
函数将信号发送到当前线程,在本例中为thread_job
线程.所以主线程永远看不到信号.
In a multithreaded program, the raise
function sends a signal to the current thread, which is the thread_job
thread in this case. So the main thread never sees the signal.
您需要保存主线程的线程ID,然后使用pthread_kill
向该线程发送信号.
You need to save off thread ID of the main thread, then use pthread_kill
to send a signal to that thread.
添加新的全局变量:
pthread_t main_tid;
然后在开始新线程之前在
Then populate it in your init
function before starting the new thread:
void init()
{
main_tid = pthread_self();
...
然后在message_rcvd
中,使用pthread_kill
:
if(pthread_kill(main_tid, SIGUSR1) == 0)
printf("raised!\n");
此外,删除thread_job
中end
的定义,并删除init
中tid
的定义.这些定义掩盖了同名的全局变量.
Also, remove the definition of end
in thread_job
, and remove the definition of tid
in init
. These definitions mask the global variables of the same name.
示例输出:
Setting timer...
Input message:hello
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [hello
]
Setting timer...
test
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [test
]
Setting timer...
Received SIGALRM: Timeout
Stopping timer...