summaryrefslogtreecommitdiff
path: root/regress/lib/libpthread/pthread_atfork/pthread_atfork.c
blob: dfc416e82c978d46688acea83c95d60fdbc41ff7 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*	$OpenBSD: pthread_atfork.c,v 1.3 2005/11/05 04:28:46 fgsch Exp $	*/

/*
 * Federico Schwindt <fgsch@openbsd.org>, 2005. Public Domain.
 */

#include <sys/types.h>
#include <pthread.h>
#include <unistd.h>

#include "test.h"

int cnt;

void
prepare1(void)
{
	ASSERT(cnt == 1);
	cnt--;
}

void
prepare2(void)
{
	ASSERT(cnt == 2);
	cnt--;
}

void
parent1(void)
{
	ASSERT(cnt == 0);
	cnt += 2;
}

void
parent2(void)
{
	ASSERT(cnt == 2);
	cnt -= 2;
}

void
child1(void)
{
	ASSERT(cnt == 0);
	cnt += 3;
}

void
child2(void)
{
	ASSERT(cnt == 3);
	cnt++;
}

void *
forker1(void *arg)
{
	CHECKr(pthread_atfork(prepare1, parent1, child1));

	cnt = 1;
	switch (fork()) {
	case -1:
		PANIC("fork");
		break;

	case 0:
		ASSERT(cnt == 3);
		_exit(0);

	default:
		ASSERT(cnt == 2);
		break;
	}

	cnt = 1;

	return (NULL);
}

void *
forker2(void *arg)
{
	CHECKr(pthread_atfork(prepare2, parent2, child2));

	cnt = 2;
	switch (fork()) {
	case -1:
		PANIC("fork");
		break;

	case 0:
		ASSERT(cnt == 4);
		_exit(0);

	default:
		ASSERT(cnt == 0);
		break;
	}

	cnt = 0;

	return (NULL);
}

int
main(int argc, char **argv)
{
	pthread_t tid;

	CHECKr(pthread_create(&tid, NULL, forker1, NULL));
	CHECKr(pthread_join(tid, NULL));
	ASSERT(cnt == 1);
	CHECKr(pthread_create(&tid, NULL, forker2, NULL));
	CHECKr(pthread_join(tid, NULL));
	ASSERT(cnt == 0);
	SUCCEED;
}