-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobust_mutex.c
More file actions
71 lines (59 loc) · 1.96 KB
/
Copy pathrobust_mutex.c
File metadata and controls
71 lines (59 loc) · 1.96 KB
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
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
typedef struct {
pthread_mutex_t mu;
int value;
} shared_t;
static shared_t *shared_create(void)
{
shared_t *s = mmap(NULL, sizeof(*s),
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (s == MAP_FAILED) { perror("mmap"); exit(1); }
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(&s->mu, &attr);
pthread_mutexattr_destroy(&attr);
s->value = 0;
return s;
}
int main(void)
{
shared_t *s = shared_create();
pid_t pid = fork();
if (pid < 0) { perror("fork"); return 1; }
if (pid == 0) {
/* child: acquire mutex, write a value, then die without releasing */
if (pthread_mutex_lock(&s->mu) != 0) { perror("child lock"); return 1; }
printf("[child] holding mutex, setting value = 42, dying now\n");
s->value = 42;
_exit(0); /* mutex is NOT unlocked */
}
waitpid(pid, NULL, 0);
/* parent: acquire — kernel detects dead owner, returns EOWNERDEAD */
int r = pthread_mutex_lock(&s->mu);
if (r == EOWNERDEAD) {
printf("[parent] EOWNERDEAD — previous owner died while holding lock\n");
printf("[parent] recovered value: %d\n", s->value);
/* mark mutex consistent so it can be reused */
if (pthread_mutex_consistent(&s->mu) != 0) {
perror("pthread_mutex_consistent"); return 1;
}
} else if (r != 0) {
fprintf(stderr, "unexpected lock error: %d\n", r);
return 1;
}
s->value = 99;
printf("[parent] continuing normally, value = %d\n", s->value);
pthread_mutex_unlock(&s->mu);
munmap(s, sizeof(*s));
return 0;
}