I want to use setitimer()
(or less probable, the alarm()
) in multithreaded process in linux 2.6+ with NPTL-enabled libc. Which thread will receive sigalarm (SIGALRM)
from kernel?
Thanks.
2014-04 update: How should I set the setitimer()
in multithreaded program, if I want to write a profiling utility like gperftools's cpuprofile; but in my tool I want to support both dynamically linked programs (so it is possible to inject my own library to init profiling) and statically linked programs (without the possibility of doing ^^^^^^).
My current profiling tool works with setting setitimer
just after fork()
and before exec()
, and it also uses ptrace
to get control over the target program and to hijack SIGPROF/SIGVPROF/SIGALRM generated by the setitimer
. I have no exact idea how it works with multithreaded programs.
From signal(7) man page:
Now, alarm(2) man page says that:
So, the signal is delivered to a process (a signal might be directed at certain thread too) and thus you do not know which of the threads will receive it.
The same with setitimer(2):
You could block
SIGALARM
in all your threads except one, then you could be certain that it will be delivered to that only thread. Assuming you are using pthreads, you can block signals with pthread_sigmask().There was interesting topic in LKML in 2010 https://lkml.org/lkml/2010/4/11/81: "setitimer vs. threads: SIGALRM returned to which thread? (process master or individual child)" by Frantisek Rysanek (cz). Author says that
setitimer
used per-thread signals at least in times before Fedora 5:But in more recent Fedoras the behavior was changed ("man pthreads", ..."Threads do not share interval timers (fixed in kernel 2.6.12).")
In the topic, Andi Kleen (Intel) recommends to switch to "POSIX timers (
timer_create
)"; and in ML thread Davide Libenzi suggests use oftimerfd
(timerfd_create, timerfd_settime) on non-ancient Linuxes.