I have 2 threads (thread1 and thread2). And I have a signal location for SIGINT . Whenever a SIGINT occurs, stream 2 must process the signal. For this, I wrote a program below
void sig_hand(int no) //signal handler { printf("handler executing...\n"); getchar(); } void* thread1(void *arg1) //thread1 { while(1) { printf("thread1 active\n"); sleep(1); } } void * thread2(void * arg2) //thread2 { signal(2, sig_hand); while(1) { printf("thread2 active\n"); sleep(3); } } int main() { pthread_t t1; pthread_t t1; pthread_create(&t1, NULL, thread1, NULL); pthread_create(&t2, NULL, thread2, NULL); while(1); }
I compiled and ran the program. every 1 second “thread1 active” prints and every 3 seconds “thread2 active” prints.
Now I generated SIGINT . But it prints the messages "thread1 active" and "thread2 active" as above. I generated SIGINT again, now every 3 seconds only the message "thread2 active" is printed. I generated SIGINT again, now all threads are blocked.
So, I realized that for the first time the main thread executes a signal handler. The second time, thread1 executes a signal handler, and finally, thread 2 executes a signal handler.
How can I write code, like whenever a signal occurs, only thread2 should execute my signal handler?
source share