Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. /* sig4.c - an example from the Solaris 2 manual.
  2.      The following sample C code creates a thread (sigint) to  handle  the
  3.      receipt of the SIGINT signal.
  4.      In Solaris2 compile with -D_POSIX_PTHREAD_SEMANTICS switch.
  5.  */
  6. #include <pthread.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. #include <signal.h>
  12.  
  13. static void *threadTwo(void *);
  14. static void *threadThree(void *);
  15. static void *sigint(void *);
  16. sigset_t signalSet;
  17. static void *threadTwo(void *arg)
  18. {
  19.  printf("hello world, from threadTwo [tid: %lu]\n",
  20.                 (unsigned long)pthread_self());
  21. while(1)
  22. {
  23.     printf(" . ");
  24.     usleep(1000);
  25.  
  26. }
  27.  
  28.  pthread_exit((void *)0);
  29. }
  30.  
  31. void *sigint(void *arg)
  32. {
  33.  int sig;
  34.  int err;
  35.  
  36.  printf("thread sigint [tid: %lu] awaiting SIGINT\n",
  37.                 (unsigned long)pthread_self());
  38.  
  39.  /*
  40.     * use POSIX sigwait() -- 2 args: signal set, signum
  41.     */
  42.     while(1){
  43.  err = sigwait(&signalSet, &sig);
  44.  
  45.  //sigemptyset(&signalSet);
  46.  
  47. // sets = pthread_sigmask(SIG_SETMASK, &signalSet, NULL);
  48. printf("received signal is %d \n",sig );
  49.  /* test for SIGINT; could catch other signals */
  50.  if (sig == SIGINT)
  51.  {
  52.      printf("\nSIGINT signal %d caught by sigint thread [tid: %lu]\n",
  53.                  sig, (unsigned long)pthread_self());
  54.                     exit(0);
  55.       pthread_exit((void *)0);
  56.  
  57.     }
  58. }
  59.  
  60. }
  61.  
  62. void error(char *message)
  63. {
  64.  perror(message);
  65.  kill(0, SIGTERM);
  66.  exit(EXIT_FAILURE);
  67. }
  68.  
  69. int main(void)
  70. {
  71.  pthread_t t1;
  72.  pthread_t t2;
  73.  pthread_t t3;
  74.  
  75.  sigfillset(&signalSet);
  76.  /*
  77.     * Block signals in initial thread. New threads will
  78.     * inherit this signal mask.
  79.     */
  80.     sigprocmask(SIG_SETMASK, &signalSet, NULL);
  81.  //pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
  82.  
  83.  if (pthread_create(&t1, NULL, sigint, NULL))
  84.      error("t1");
  85.  
  86.  printf("Creating threads\n");
  87.  printf("##################\n");
  88.  printf("press CTRL-C to deliver SIGINT to sigint thread\n");
  89.  printf("##################\n");
  90.  
  91. while(1)
  92. {
  93. printf(" . ");
  94. usleep(10000);
  95. }
  96.  if (pthread_join(t1, NULL))
  97.      perror("join");
  98.  printf("Bye!\n");
  99.  return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement