且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待信号,然后继续执行

更新时间: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_jobend的定义,并删除inittid的定义.这些定义掩盖了同名的全局变量.

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...