Skip to content
Advertisement

Wait for signal, then continue execution

I am trying to make a program that suspends its execution until a signal arrives. Then, after the signal arrives I just want my code to continue its execution from where it was. I don’t want it to execute a function handler or whatsoever. Is there a simple way of doing this? I have been struggling for a week or so, reading here and there, and didn’t manage to get a fully operative code.

In particular, I want the main program to create a thread that waits for some particular event to happen (e.g., a user has input some data to stdin). Meanwhile, the main program is doing something but at some point it suspends its execution until it receives a signal.

The signal may come from the thread because it has detected the event or it may be due to a timeout because I don’t want it to wait for ever.

I have made some code but it does not work as expected…

JavaScript

Here is a typical execution of this code.

JavaScript

As you can see, the signal SIGUSR1 is being raised and sigwait is being unblocked. However, the code seems does not continue after the signal has been raised. (Note that I don’t need a signal handler but I just added for the debugging purposes. I have blocked its execution with sigprocmask)

Why is SIGUSR1 unblocking sigwait but the execution does not continue from there? Is there a way to make it continue after unblocking? This seems to work for SIGALRM but why not for SIGUSR1?

As I said, I have been looking at tons of stackoverflow questions, online howto’s, tried with different system calls (e.g., pause, sigsuspend), … but couldn’t find a way to solve this 🙁

If you are wondering why I am not doing this code much simpler by not using a thread is because this is not actually the code I am implementing but just a simpler example to make my question more clear. I am actually trying to implement a network protocol API, similar to the sockets API for my own protocol.

Thanks in advance

Advertisement

Answer

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:

JavaScript

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

JavaScript

Then in message_rcvd, use pthread_kill:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement