-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy path12.9.c
73 lines (60 loc) · 1.61 KB
/
12.9.c
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
68
69
70
71
72
73
#include <pthread.h>
#include "apue.h"
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void) {
int err;
printf("preparing locks...\n");
if ((err = pthread_mutex_lock(&lock1)) != 0) {
err_cont(err, "can't lock lock1 in prepare handler");
}
if ((err = pthread_mutex_lock(&lock2)) != 0) {
err_cont(err, "can't lock lock2 in prepare handler");
}
}
void parent(void) {
int err;
printf("parent unlocking locks...\n");
if ((err = pthread_mutex_unlock(&lock1)) != 0) {
err_cont(err, "can't unlock lock1 in parent handler");
}
if ((err = pthread_mutex_unlock(&lock2)) != 0) {
err_cont(err, "can't unlock lock2 in parent handler");
}
}
void child(void) {
int err;
printf("child unlocking locks...\n");
if ((err = pthread_mutex_unlock(&lock1)) != 0) {
err_cont(err, "can't unlock lock1 in child handler");
}
if ((err = pthread_mutex_unlock(&lock2)) != 0) {
err_cont(err, "can't unlock lock2 in child handler");
}
}
void *thr_fn(void *arg) {
printf("thread started...\n");
pause();
return (0);
}
int main(void) {
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0) {
err_exit(err, "can't install fork handlers");
}
if ((err = pthread_create(&tid, NULL, thr_fn, 0)) != 0) {
err_exit(err, "can't create thread");
}
sleep(2);
printf("parent about to fork...\n");
if ((pid = fork()) < 0) {
err_quit("fork error");
} else if (pid == 0) {
printf("child returned from fork\n");
} else {
printf("parent returned from fork\n");
}
exit(0);
}