Wait for signal, then continue execution

旧巷老猫 提交于 2019-12-04 10:51:50

The SIGUSR1 signal isn't going where you think it is.

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.

You need to save off thread ID of the main thread, then use pthread_kill to send a signal to that thread.

Add a new global:

pthread_t main_tid;

Then populate it in your init function before starting the new thread:

void init()
{
    main_tid = pthread_self();
    ...

Then in message_rcvd, use pthread_kill:

    if(pthread_kill(main_tid, SIGUSR1) == 0)
        printf("raised!\n");

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.

Sample output:

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...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!