Skip to content

Commit

Permalink
pthreads/sigwait: handle SIGHUP in another thread
Browse files Browse the repository at this point in the history
Signed-off-by: Stefan Naewe <stefan.naewe@atlas-elektronik.com>
  • Loading branch information
Stefan Naewe committed Aug 31, 2010
1 parent 84612e1 commit f5cbfa5
Showing 1 changed file with 50 additions and 5 deletions.
55 changes: 50 additions & 5 deletions pthreads/sigwait.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int interrupted = 0;
sigset_t signal_set;

/*
* Wait for the SIGINT signal. When it has occurred 5 times, set
Expand All @@ -25,7 +24,10 @@ void *signal_waiter (void *arg)
int sig_number;
int signal_count = 0;
int status;

sigset_t signal_set;

sigfillset(&signal_set);
sigdelset(&signal_set, SIGHUP);
while (1) {
sigwait (&signal_set, &sig_number);
if (sig_number == SIGINT) {
Expand All @@ -44,14 +46,52 @@ void *signal_waiter (void *arg)
break;
}
}
else {
printf("Ignoring signal %d\n", sig_number);
}
}
return NULL;
}

void *signal_waiter2 (void *arg)
{
int sig_number;
int signal_count = 0;
int status;
sigset_t signal_set;

sigfillset(&signal_set);
sigdelset(&signal_set, SIGINT);
while (1) {
sigwait (&signal_set, &sig_number);
if (sig_number == SIGHUP) {
printf ("Got SIGHUP (%d of 5)\n", signal_count+1);
if (++signal_count >= 3) {
status = pthread_mutex_lock (&mutex);
if (status != 0)
err_abort (status, "Lock mutex");
interrupted = 1;
status = pthread_cond_signal (&cond);
if (status != 0)
err_abort (status, "Signal condition");
status = pthread_mutex_unlock (&mutex);
if (status != 0)
err_abort (status, "Unlock mutex");
break;
}
}
else {
printf("Ignoring signal %d\n", sig_number);
}
}
return NULL;
}

int main (int argc, char *argv[])
{
pthread_t signal_thread_id;
pthread_t signal_thread_id, signal_thread_id2;
int status;
sigset_t signal_set;

/*
* Start by masking the "interesting" signal, SIGINT in the
Expand All @@ -64,8 +104,7 @@ int main (int argc, char *argv[])
* while the sigwaiter is not blocked in sigwait might be
* delivered to another thread.
*/
sigemptyset (&signal_set);
sigaddset (&signal_set, SIGINT);
sigfillset (&signal_set);
status = pthread_sigmask (SIG_BLOCK, &signal_set, NULL);
if (status != 0)
err_abort (status, "Set signal mask");
Expand All @@ -78,6 +117,11 @@ int main (int argc, char *argv[])
if (status != 0)
err_abort (status, "Create sigwaiter");

status = pthread_create (&signal_thread_id2, NULL,
signal_waiter2, NULL);
if (status != 0)
err_abort (status, "Create sigwaiter");

/*
* Wait for the sigwait thread to receive SIGINT and signal
* the condition variable.
Expand All @@ -96,3 +140,4 @@ int main (int argc, char *argv[])
printf ("Main terminating with SIGINT\n");
return 0;
}

0 comments on commit f5cbfa5

Please sign in to comment.