Pass arguments to signal handler in C

2019-07-20 09:01发布

问题:

How can I pass arguments (e.g. a pointer to a struct) to a signal handler? I'm writing a multithread application, so I cannot use global variables

I associate a timer to each thread. When timer expires I have to update a struct (each thread has a different struct).

How can I do?

回答1:

The way the signal handler is called by the system is fixed -- there's no way to change it and add an additional user pointer. So if you want to get additional data into the signal handler, the only way to do it is with a global variable (which could be thread-local).

However, if you are trying to use timer_create with threads, you are much better off using SIGEV_THREAD rather than SIGEV_SIGNAL. The latter sends the signal to the process rather than the thread, so it might be caught by any thread in the process.



回答2:

POSIX timers allow to specify the details of how your process will be notified of an expiration using the struct sigevent structure documented in sigevent(7).

To pass context info to the siggnal handler for the generated signal, you can set the .sigev_value.sival_ptr member, which your signal handler will then be able to retrieve (you'll need to set the signal handler via the .sa_sigaction member of struct sigaction, while making sure the structure's .sa_flags is ORred with SA_SIGACTION).