Creating a thread in signal handlers - c

In my program I need to perform some action upon timer (timer_create()) expiration. I want to perform this action by spawning a new thread. So I want to know if it is safe to create a thread in signal handlers?

Signal handlers may not call non re-entrant functions. You should look at your o/s documentation but creating a thread is unlikely to be re-entrant. On linux, man -s7 signal gives you a list of safe to call functions, which doesn't include anything from pthread.
Really all a signal handler should do is to set a flag for the main code or a signal handling thread to read. More than that gets risky.

Related

C write async unsafe code in signal handler

How can i run asynchrounous-unsafe code in a signal handler. I cant use a flag in my case. Could i use longjmp to jump to a different context?
In a signal handler you can only use a set of safe functions which in many cases is sufficient for complicated functionality started within a handler. You can check man pages for your system for 'signal-safety' or similar. Here is a pointer on the web: https://man7.org/linux/man-pages/man7/signal-safety.7.html
pthread synchronization functions are not on the list.
However, One of the function listed there is sem_post: https://man7.org/linux/man-pages/man3/sem_post.3.html
sem_post() is async-signal-safe: it may be safely called within a
signal handler.
So, you can implement mutex-like synchronization using semaphores within the signal handler.

Do signal handlers need to be included in every possible context in a process?

For example:
Say I have a signal handler in main() that handles a timer alarm. I also have worker threads that main creates, which do not have this signal handler because the logic required for the signal is contained in main. I believe this will be a problem, because if one of the worker threads is currently running when the signal is sent, it will catch the signal and not have the required signal handler to handle it. But it seems like overkill to include definitions of every single relevant custom signal handler in every possible context. Am I missing something?
Say I have a signal handler in main() that handles a timer alarm.
No, you don't. A signal handler is a function, and C has no meaningful sense in which one function can be inside another.
I also have worker threads that main creates, which do not have this signal handler because the logic required for the signal is contained in main.
Signal dispositions, including custom handlers, are process-wide properties. You cannot have different dispositions for the same signal in different threads of the same process. Moreover, no, the logic for handling a signal is in its signal handler, if it has one, or in the kernel if it doesn't. The functions available to a process are also a per-process property, not a per-thread property.
I believe this will be a problem, because if one of the worker threads is currently running when the signal is sent, it will catch the signal and not have the required signal handler to handle it.
Not necessarily, and no.
Every thread has its own signal mask, which controls which signals may be delivered to it. A thread inherits its signal mask from its parent thread, and can subsequently modify that mask via the pthread_sigmask() function. This way you can control in which thread your signal handlers run and, at least as importantly, which threads can be interrupted by signals, so it is not necessarily the case that signals will be delivered to your worker threads.
But also no, individual threads do not have separate signal handlers in any case, as I already discussed. Every thread has all the signal handlers the process has, because they belong to the process, not to individual threads.
But it seems like overkill to include definitions of every single relevant custom signal handler in every possible context. Am I missing something?
Yes. I'm not sure exactly which parts you're missing, but see above.
A signal handler is code, which is shared by all of your threads because all the threads share the process' memory space. Hence, there's no way it will "not have the signal handler".
Now there might be linkage from the signal handler to the code that runs in one particular thread and that's something your program needs to handle through the design of your code and data structures.
Assuming you're interested in posix/linux systems, it is possible to mask signals on a per-thread basis with pthread_sigmask. One common solution therefore is to block signals in all threads except those that are expecting to handle them.
Some signals are inherently thread-specific (such as floating point exceptions and segmentation violations). See the signal(7) man page for more info.

Multithreading - Calling a function after a specific time by each thread

I want all of the threads (in a multithreaded C code running on Linux) to call a function after a specific time . I tried alarm(). It is not thread safe: Only one SIGALRM generation can be scheduled in this manner. If the SIGALRM signal has not yet been generated, the call shall result in rescheduling the time at which the SIGALRM signal is generated.Is there any way to implement such functionality and guarantee that the thread would call the function and leave its current task at that time?
Do you have an array with all the pthread_ts of the other threads? If so, iterate on the array and use pthread_kill to send the signal to the other threads.
You can do this in the main thread, or in a separate thread.
Be careful that there's not much that you can safely do in a signal handler. No I/O except for write, in particular.

Is alarm(unsigned int second) function thread_safe?

With alarm function, I want to implement UDP retransmission. Is this function thread safe? Will it work under multi-threaded environment.
Calling alarm() in a thread will not reset pending signals, so you probably don't want to call it in a thread. You'd only want to call it within the parent no matter what language you are using if the underlying functionality is pthreads.
You'd probably be better off making provisions in a structure shared with the threads to re-send data as needed, or poke all (or some) running threads to resend upon servicing the signal in the parent.
I can't think of an implementation where calling it within a thread would be a good idea, so no - I wouldn't use it that way.
alarm() function is not thread safe.
Because it is process level. You can't control which thread should receive the signal once timer triggers. So at the time of signal arrival, another thread may be running. Sometimes it may crash you program with SIG_SEGV.
According to the docs alarm is "process-level" and only the last call is active... it uses the SIGNAL model and sends an async SIGALARAM to the process... whether the called signal handler is threadsafe depends on your implementation...

Race condition in C signal handlers puzzle

I need to know how to avoid a race condition when handling signals in C. Each time my program receives a signal, I want it to alter a (global) linked list. It is vitally important that I not miss a signal, and equally important that the global linked list I'm modifying not be changed while the handler is executing.
The problem is, if I receive a signal, and start the handler, but am then interrupted by another signal. This (as I understand it) triggers a new execution of the signal handler, which will operate on the same global dataset - not permissible!
I can't use a lock, because if the first handler call is interrupted, it will naturally never free the lock for the interrupting handler to pick up. So, how do I do it? Any idea?
If you have the luck to be working in a multi-threaded environment, one of the best ways is to have the global linked list controlled exclusively by a separate thread. Interrupts would enqueue requests to this thread (something that would be executed very quickly, say, by simply passing a pointer), and then the thread would procedurally go through each request and modify the linked list. This allows lockless execution.
Of course, you have to rely on your OS's message passing junk, so that may not be an option.
You can mask signals while executing signal handler - check sa_mask field of struct sigaction you pass to sigaction() syscall.
From http://users.evtek.fi/~tk/rtp/signals-programming.html:
The way to guarantee no races at all, is to let the system set the signal masking for us before it calls the signal handler. This can be done if we use the sigaction() system call to define both the signal handler function AND the signal mask to be used when the handler is executed. You would probably be able to read the manual page for sigaction() on your own, now that you're familiar with the various concepts of signal handling. On old systems, however, you won't find this system call, but you still might find the sigvec() call, that enables a similar functionality.
I think you should seriate the signal.just like the work queue
E.g. all the signal should put into a work queue(FIFO), and then the executing thread poll the queue all the time. if the queue is not empty,this thread will pick the top signal and start it`s handler. keep doing like that, until the queue is empty.

Resources