windows-build-updates-20030314
[openafs.git] / src / util / softsig.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #define _POSIX_PTHREAD_SEMANTICS
11 #include <afs\param.h>
12 #include <assert.h>
13 #include <stdio.h>
14 #ifndef  AFS_NT40_ENV
15 #include <signal.h>
16 #include <unistd.h>
17 #else
18 #include <afs\procmgmt.h>
19 #endif
20 #include <pthread.h>
21
22 static pthread_t softsig_tid;
23 static struct {
24   void (*handler) (int);
25   int pending;
26 } softsig_sigs[NSIG];
27
28 static void *
29 softsig_thread (void *arg)
30 {
31   sigset_t ss;
32
33   sigemptyset (&ss);
34   sigaddset (&ss, SIGUSR1);
35
36   while (1) {
37     void (*h) (int);
38     int i, sigw;
39
40     h = NULL;
41
42     for (i = 0; i < NSIG; i++)
43       if (softsig_sigs[i].pending) {
44         softsig_sigs[i].pending = 0;
45         h = softsig_sigs[i].handler;
46         break;
47       }
48
49     if (i == NSIG)
50       assert (0 == sigwait (&ss, &sigw));
51     else if (h)
52       h (i);
53   }
54 }
55
56 void
57 softsig_init ()
58 {
59   sigset_t ss, os;
60
61   sigemptyset (&ss);
62   sigaddset (&ss, SIGUSR1);
63
64   /* Set mask right away, so we don't accidentally SIGUSR1 the
65    * softsig thread and cause an exit (default action).
66    */
67   assert (0 == pthread_sigmask (SIG_BLOCK, &ss, &os));
68   assert (0 == pthread_create (&softsig_tid, NULL, &softsig_thread, NULL));
69   assert (0 == pthread_sigmask (SIG_SETMASK, &os, NULL));
70 }
71
72 static void
73 softsig_handler (int signo)
74 {
75   softsig_sigs[signo].pending = 1;
76   pthread_kill (softsig_tid, SIGUSR1);
77 }
78
79 void
80 softsig_signal (int signo, void (*handler) (int))
81 {
82   softsig_sigs[signo].handler = handler;
83   signal (signo, softsig_handler);
84 }
85
86 #if defined(TEST)
87 static void
88 print_foo (int signo)
89 {
90   printf ("foo, signo = %d, tid = %d\n", signo, pthread_self ());
91 }
92
93 int
94 main ()
95 {
96   softsig_init ();
97   softsig_signal (SIGINT, print_foo);
98   printf ("main is tid %d\n", pthread_self ());
99   while (1)
100     sleep (60);
101 }
102 #endif