/*
 * sigwait.c.1   Tests the sigwait() service.  Create 4 sigwaiters each of
 *               which will wait for the SIGINT, SIGTERM, SIGHUP, and SIGQUIT 
 *               signals.
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "utils.h"

#define THREADS ((int) 4)
extern int getpid( void );

void
waiter( void )
{
	sigset_t sigset;
	int caught = FAILURE;

   sigemptyset( &sigset );
   sigaddset( &sigset, SIGINT );
   sigaddset( &sigset, SIGTERM );
   sigaddset( &sigset, SIGHUP );
   sigaddset( &sigset, SIGQUIT );

   pthread_sigmask( SIG_SETMASK, &sigset, NULL );

	switch((caught = sigwait( sigset )))
	{
	  case SIGINT:
		print_str("Caught SIGINT");
		break;
	  case SIGTERM:
		print_str("Caught SIGTERM");
		break;
	  case SIGHUP:
		print_str("Caught SIGHUP");
		break;
	  case SIGQUIT:
		print_str("Caught SIGQUIT");
		break;
	  default:
                printf("Error: %d\n", caught );
		break;

	}

	pthread_exit( (void *) caught );
}

static pthread_t th[THREADS];

int 
main( int argc, char *argv[] )
{
   int exit_status, st, i;
   pthread_attr_t attr;

   printf("pid %d: Blocked %d %d %d %d\n", 
		   getpid(), SIGINT, SIGQUIT, SIGHUP, SIGTERM );

   /*
    * Create some joinable threads each of which will inherit the
	* main threads mask of blocked signals.
    */
   st = pthread_attr_init( &attr );
   CHECK( st, "pthread_attr_init()");

   st = pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
   CHECK( st, "pthread_attr_setdetachstate()");
   for(i = 0; i < THREADS; i++ )
   {
	   st = pthread_create( &th[i], &attr, (thread_proc_t) waiter, NULL ); 
	   CHECK(st, "pthread_create()");
   }

   for(i = 0; i < THREADS; i++ )
   {
       st = pthread_join( th[i], (void **) &exit_status );
       CHECK( st, "pthread_join()");
   }

   st = pthread_attr_destroy( &attr );
   CHECK( st, "pthread_attr_destroy()");

   return( EXIT_SUCCESS );
}





