1717
1818pthread_cond_t started_cond = PTHREAD_COND_INITIALIZER ;
1919pthread_mutex_t started_lock = PTHREAD_MUTEX_INITIALIZER ;
20- _Atomic bool got_term_signal = false;
20+ _Atomic bool got_sigterm = false;
21+ _Atomic bool got_sigusr1 = false;
2122
22- pthread_t thr ;
23+ pthread_t main_thread ;
24+ pthread_t child_thread ;
2325
2426void signal_handler (int sig , siginfo_t * info , void * arg ) {
25- printf ("signal: %d onthread=%d\n" , sig , pthread_self () == thr );
27+ printf ("signal: %d onthread=%d\n" , sig , pthread_self () == child_thread );
2628 if (sig == SIGTERM ) {
27- got_term_signal = true;
29+ got_sigterm = true;
30+ } else if (sig == SIGUSR1 ) {
31+ got_sigusr1 = true;
2832 }
2933}
3034
@@ -34,6 +38,7 @@ void setup_handler() {
3438 act .sa_flags = SA_SIGINFO ;
3539 act .sa_sigaction = signal_handler ;
3640 sigaction (SIGTERM , & act , NULL );
41+ sigaction (SIGUSR1 , & act , NULL );
3742}
3843
3944
@@ -46,17 +51,26 @@ void *thread_start(void *arg) {
4651 pthread_cond_signal (& started_cond );
4752 pthread_mutex_unlock (& started_lock );
4853 // As long as this thread is running, keep the shared variable latched to nonzero value.
49- while (!got_term_signal ) {
54+ while (!got_sigterm ) {
5055 sleepms (1 );
5156 }
52- printf ("got term signal, shutting down thread\n" );
53- pthread_exit (0 );
57+ printf ("got term signal, sending signal back to main thread\n" );
58+ pthread_kill (main_thread , SIGUSR1 );
59+ return NULL ;
5460}
5561
5662int main () {
63+ main_thread = pthread_self ();
5764 setup_handler ();
5865
59- int s = pthread_create (& thr , NULL , thread_start , 0 );
66+ printf ("tesing pthread_kill with pthread_self\n" );
67+ assert (!got_sigterm );
68+ int s = pthread_kill (pthread_self (), SIGTERM );
69+ assert (got_sigterm );
70+ got_sigterm = false;
71+ assert (s == 0 );
72+
73+ s = pthread_create (& child_thread , NULL , thread_start , 0 );
6074 assert (s == 0 );
6175
6276 // Wait until thread kicks in and sets the shared variable.
@@ -65,11 +79,15 @@ int main() {
6579 pthread_mutex_unlock (& started_lock );
6680 printf ("thread has started, sending SIGTERM\n" );
6781
68- s = pthread_kill (thr , SIGTERM );
82+ s = pthread_kill (child_thread , SIGTERM );
6983 assert (s == 0 );
7084 printf ("SIGTERM sent\n" );
7185
72-
73- pthread_join (thr , NULL );
86+ pthread_join (child_thread , NULL );
87+ printf ("joined child_thread\n" );
88+ while (!got_sigusr1 ) {
89+ sleepms (1 );
90+ }
91+ printf ("got SIGUSR1. all done.\n" );
7492 return 0 ;
7593}
0 commit comments