1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
| #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#define THREAD_SLEEP(ms) {\
struct timespec delay, rem ;\
delay.tv_sec = ms / 1000 ;\
delay.tv_nsec = ((ms % 1000)*1000000) ;\
while(nanosleep(&delay, &rem) == -1 && errno == EINTR) delay = rem;\
}
pthread_t th1 ;
pthread_t th2 ;
void signalHandler(int arg)
{
printf("\nsignalHandler\n");
printf("\nsignalHandler(): %lu\n", pthread_self());
pthread_exit(0);
}
void* threadFunction1(void* arg)
{
printf("\nthreadFunction1(): %lu\n", pthread_self());
printf("\nthreadFunction1\n");
while(1)
{
printf("1");
THREAD_SLEEP(10);
}
return NULL ;
}
void* threadFunction2(void* arg)
{
printf("\nthreadFunction2(): %lu\n", pthread_self());
printf("\nthreadFunction2\n");
while(1)
{
printf("2");
THREAD_SLEEP(10);
}
return NULL ;
}
int main(void)
{
printf("\nmain(): %lu\n", pthread_self());
struct sigaction newact ;
newact.sa_handler = signalHandler ;
sigaction(SIGALRM, &newact, NULL);
pthread_create(&th1, NULL, &threadFunction1, NULL) ;
pthread_create(&th2, NULL, &threadFunction2, NULL) ;
sleep(1);
pthread_kill( th1, SIGALRM );
pthread_join(th1, NULL );
printf("\njoin1\n");
sleep(1);
pthread_kill( th2, SIGALRM );
pthread_join(th2, NULL );
printf("\njoin2\n");
return 0 ;
}
|