Revisiting this question:
I have multiple threads running (pthreads api), each with it's own timer that calls a function handler(int signum) after a certain interval. As these threads call handler and within the function handler, how do I know which thread called it? Is thread-specific data required?
I notice that the thread that enters the handler function is a different thread from the one that set it up, so calling pthread_self() doesn't work. How do I get around this?
Here is a small example illustrating the problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
void handler(int);
void call_alarm();
void *setup(void*);
pthread_t p;
void handler(int signum)
{
printf("handler thread %lu\n", pthread_self());
}
void call_alarm()
{
static struct itimerval timer;
static struct sigaction sa;
printf("call_alarm %lu\n", (unsigned long)pthread_self());
sa.sa_handler = handler;
sa.sa_flags = SA_RESETHAND;
timer.it_value.tv_usec = 500;
timer.it_value.tv_sec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
sigaction(SIGALRM, &sa, 0);
setitimer(ITIMER_REAL, &timer, 0);
}
void *setup(void *param)
{
while(1)
{
printf("caller thread %lu\n", pthread_self());
call_alarm();
pause();
}
}
int main(void)
{
if(pthread_create(&p, NULL, setup, NULL));
while(1);
return 0;
}
Output:
caller thread 3086637968
call_alarm 3086637968
handler thread 3086640832
As you can see it prints out different values.
You can print the thread ID when the handler is called:
On Linux: gettid()
On Windows GetCurrentThreadId().
and if you can't, write a function wrapper around the handler and tell your code to call the wrapper function instead of calling the handler directly.
The POSIX chapter on Signal Generation and Delivery states:
At the time of generation, a determination shall be made whether the signal has been generated for the process or for a specific thread within the process. Signals which are generated by some action attributable to a particular thread, such as a hardware fault, shall be generated for the thread that caused the signal to be generated. Signals that are generated in association with a process ID or process group ID or an asynchronous event, such as terminal activity, shall be generated for the process.
I wonder if the SIGALRM signal you're catching is not considered a action attributable to a particular thread, such as a hardware fault. It sounds like your SIGALRM signal falls into the second category, and is being generated for the process.
Related
I'm working on a application that has specific timing restraints such that an event should occur (ideally exactly) every 200us. I'm trying to do this with a timer and signal.
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
timer_t timer_id;
void start_timer(void)
{
struct itimerspec value;
value.it_value.tv_sec = 0;
value.it_value.tv_nsec = 20000;
value.it_interval.tv_sec = 0;
value.it_interval.tv_nsec = 200000;
timer_create(CLOCK_REALTIME, NULL, &timer_id);
timer_settime(timer_id, 0, &value, NULL);
}
void handler(int sig) {
printf("in handler\n");
}
void *my_thread(void *ignore)
{
(void)ignore;
start_timer();
// Sleep forever
while(1) sleep(1000);
}
int main()
{
pthread_t thread_id;
(void) signal(SIGALRM, handler);
pthread_create(&thread_id, NULL, my_thread, NULL);
// sleep is a placeholder for this SO question. I want to do
// other processing here
sleep(5000);
printf("sleep finished\n");
}
After 200us the signal handler is called. It appears to be called when the sleep(5000) line is running because the "sleep finished" message is displayed early. I want the timer to disrupt the thread that started the timer, not the main process. This is why I created a thread to start it. Is there a way to have the signal only abort the current instruction on the thread instead of on the main process? I know that the other threads/processes will be blocked when the handler runs, but I wanted them to continue afterwards as if nothing happened. For example, in this case I want to sleep at least 5000 seconds.
Yes, you can block the signal (pthread_sigmask) in the main thread before starting any other threads, and only unblock it in the thread intended to handle it. This will ensure that it arrives in the thread you want it in.
However, if you already have threads, are you sure you actually need a timer generating a signal for this? clock_nanosleep should allow sleep with wakeup at a precise time, and avoids all the awfulness of signals.
I have some practical questions about the settimer() and SIGALRM and how they work .
Let's say that I have some threads created: (EDITED)
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <signal.h>
pthread_mutex_t lock;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void timer_handler (int signum)
{
printf ("\n[WAITING LINE] All our assistants are busy at the moment,we apologize. Please wait on the line\n");
}
void* threadFunc(void* arg){
struct itimerval timer;
if (signal(SIGALRM, (void (*)(int)) timer_handler) == SIG_ERR) {
perror("Unable to catch SIGALRM");
exit(1);
}
timer.it_value.tv_sec =1;
timer.it_value.tv_usec = 0;
while(mycond){
if(setitimer (ITIMER_REAL, &timer, NULL)){
perror("error calling setitimer()");
exit(1);
}
pthread_cond_wait(&cond1,&lock);
//doing other things that take significant time
}
}
int main(){
//initializing mutex
....
//creating the threads
....
//waiting the threads to join
....
return 0;
}
I don't get the message I was supposed to see displayed every 20 msec.
In the example I followed a while(1) was implemented after the settimer but
I can't do that because I want this message displayed while my thread waits for the condition signal.
It doesn't really matter what is implemented in the rest code , let's assume it takes far more time than 20ms to finish and signal the condition.
What should I do to take the timer_handler message every 20ms while the condition is not signaled yet?
I am new to using both condition variables and settimer() so any help to understand them and solve any misunderstaning would be appreciated .
If all your threads are blocked, the virtual timer's clock will not be running.
You might need to switch to ITIMER_REAL. (Also beware that you shouldn't be using async-signal unsafe functions such as printf inside a signal handler.)
I am building a pre-emptive userspace thread scheduler which uses a timer to interrupt threads and switch between them according to priority. However, once a thread is interrupted, I cannot seem to let it finish; only start it again. Is what I am asking for even possible using swapcontext? The result of this code, which should allow itake5seconds() to complete, just loops the "Hello" message over and over.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <ucontext.h>
static ucontext_t mainc, newthread;
void itake5seconds()
{
puts("Hello. I take 5 seconds to run.");
sleep(5);
puts("And I'm done! Wasn't that nice?");
}
void timer_handler(int signum)
{
puts("Doing some scheduler stuff.");
swapcontext(&mainc, &newthread);
}
int main(int argc, char* argv[])
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM, &sa, NULL);
getcontext(&newthread);
newthread.uc_stack.ss_sp = malloc(5000);
newthread.uc_stack.ss_size = 5000;
newthread.uc_link = &mainc;
makecontext(&newthread, &itake5seconds, 0);
struct itimerval timer;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 500000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 500000;
setitimer(ITIMER_REAL, &timer, NULL);
while(1);
return 0;
}
Your code is calling an "unsafe" function in the signal handler (swapcontext). Therefor, the behavior of your program is "undefined".
From man 7 signal:
A signal handler function must be very careful, since processing elsewhere may be interrupted at some arbitrary point in the execution of the program. POSIX has the concept of "safe function". If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined.
See the "Example for SVID Context Handling" section in Complete Context Control for an example of how you can work this with a signal handler. But basically you'd use a volatile int global variable to flag that your signal handler was called and instead do the swapcontext call from normal code (i.e. code that's not running from within the context of signal handling).
The problem was that I was not saving the current execution context that swapcontext() returns to its first parameter.
I have put a simple signal handler in my code. I have initialised the sigevent structure, with a handler function to catch the signal.
Can someone please pin-point as to why the code is not working? Ideally if there is a signal, my handler should be called. But it is not.
Please help me,
Thanks
Kingsmasher1
enter code here
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
void my_handler(int sival_int, void* sival_ptr)
{
printf("my_handler caught\n");
signal(sig,my_handler);
}
int main()
{
struct sigevent sevp;
sevp.sigev_notify=SIGEV_THREAD;
sevp.sigev_signo=SIGRTMIN;
sevp.sigev_value.sival_ptr=NULL;
sevp.sigev_notify_function=(void*)my_handler;
kill(0,SIGRTMIN); // This should invoke the signal and call the function
}
struct sigevent is not about specifying how the process will handle a signal - struct sigaction and sigaction() are how you do that. Instead, struct sigevent is used to specify how your process will be informed of some asychronous event - like the completion of asychronous IO, or a timer expiring.
The sigev_notify field specifies how the event should be notified:
SIGEV_NONE - no notification at all. The remainder of the fields are ignored.
SIGEV_SIGNAL - a signal is sent to the process. The sigev_signo field specifies the signal, the sigev_value field contains supplementary data that is passed to the signal handling function, and the remainder of the fields are ignored.
SIGEV_THREAD - a function is called in a new thread. The sigev_notify_function field specifies the function that is called, sigev_value contains supplementary data that is passed to the function, and sigev_notify_attributes specifies thread attributes to use for the thread creation. The remainder of the fields are ignored.
Note in particular that if you set SIGEV_THREAD, the sigev_signo field is ignored - the struct sigevent is about specifying either a thread or a signal as a notification method, not about specifying a thread as the way that a signal should be handled.
The struct sigevent must also be passed to a function - like timer_create() - that sets up the asychronous event that will be notified. Simply creating a struct sigevent object does not do anything special.
If you wish to use a dedicated thread to handle a signal, create the thread up front and have it loop around, blocking on sigwaitinfo(). Use sigprocmask() to block the signal in every other thread.
I think you are mixing up your signal handling idioms here, you create a sigevent structure and then do nothing with it and then use signal() within the signal handler. The following code shows a very simple signal handling routine based on your code; note that I have changed the definition of my_handler. If you need more sophisticated handling then sigaction() is probably the system call you need to look into.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
void my_handler(int sig)
{
printf("my_handler caught\n");
signal(sig,my_handler);
}
int main()
{
signal(SIGRTMIN,my_handler);
kill(0,SIGRTMIN); // This should invoke the signal and call the function
while(1) ; // Infinite loop in case the program ends before the signal gets caught!
}
This works under cygwin on my windows box (no access to a linux box at the minute).
I hope this works.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
void
my_handler (int sig)
{
printf ("my_handler caught\n");
signal (sig, my_handler);
}
int
main ()
{
int signo;
struct sigevent sevp;
sigset_t set;
if (sigemptyset (&set) == -1)
perror ("sigemptyset");
if (sigaddset (&set, SIGRTMIN) == -1)
perror ("sigaddset");
if (sigprocmask (SIG_BLOCK, &set, NULL) == -1)
perror ("sigprocmask");
sevp.sigev_notify = SIGEV_THREAD;
sevp.sigev_signo = SIGRTMIN;
sevp.sigev_value.sival_ptr = NULL;
kill (0, SIGRTMIN);
if (sigwait (&set, &signo) == 0)
my_handler (signo);
else
perror ("sigwait");
}
What happens if a program calls a function which is a cancellation point from a signal handler? There are a number of functions which POSIX specifies as both async-signal-safe and cancellation points. If a signal handler calls such a function and cancellation is acted upon, the result is quite similar to what would happen if the thread had enabled asynchronous cancellation - actually much worse, because all the cancellation cleanup handlers, which are probably not async-signal-safe, would be called from a signal-handler context.
What does POSIX actually specify in this case, and what do implementations actually do? I can't find any language in POSIX that would forbid cancellation points in signal handlers from being acted upon, nor any such protection in the glibc/nptl source.
I'm not aware that POSIX even dares to mention this topic, but I haven't done an exhaustive search.
Some brief experimentation with a gcc/nptl system reveals that, as I suspected and I think you did too, there is no such protection in NPTL - the cancellation handlers do indeed get called, from within the signal handler context.
The program below (apologies for the hackiness etc) displays the following output:
Signal handler called
Sent cancellation
Cleanup called
In sighandler
... indicating that:
the signal handler got called
the other thread then called pthread_cancel()
the cancellation handler then got called, without the signal handler completing
Here's the program:
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
pthread_t mainthread;
int in_sighandler = 0;
void
cleanup (void *arg)
{
write(1, "Cleanup called\n", strlen("Cleanup called\n"));
if (in_sighandler) {
write(1, "In sighandler\n", strlen("In sighandler\n"));
} else {
write(1, "Not in sighandler\n", strlen("In sighandler\n"));
}
}
void
sighandler (int sig, siginfo_t *siginfo, void *arg)
{
in_sighandler = 1;
write(1,"Signal handler called\n", strlen("Signal handler called\n")); // write() is a CP
usleep(3000000); // usleep() is a CP; not strictly async-signal-safe but happens to be so in Linux
write(1, "Signal handler exit\n", strlen("Signal handler exit\n"));
in_sighandler = 0;
}
void *
thread (void *arg)
{
sleep(1);
pthread_kill(mainthread, SIGUSR1);
usleep(500000);
pthread_cancel(mainthread);
printf("Sent cancellation\n");
return (NULL);
}
int
main (int argc, char **argv)
{
int rc;
struct sigaction sa;
pthread_t threadid;
mainthread = pthread_self();
// Set up a signal handler to test its cancellation properties
sa.sa_sigaction = &sighandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
rc = sigaction(SIGUSR1, &sa, NULL);
assert(rc == 0);
// Set up a thread to send us signals and cancel us
rc = pthread_create(&threadid, NULL, &thread, NULL);
assert(rc == 0);
// Set up cleanup handlers and loop forever
pthread_cleanup_push(&cleanup, NULL);
while (1) {
sleep(60);
}
pthread_cleanup_pop(0);
return (0);
}