summaryrefslogtreecommitdiff
path: root/regress/lib/libpthread/fork/fork.c
blob: 9df00128f7af34fc0d0375a90ef1f94086bb9d64 (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
/*	$NetBSD: fork.c,v 1.3 2003/07/26 19:38:48 salo Exp $	*/

/*
 * Check that child process doesn't get threads, also make sure sleep
 * works in child.
 *
 * Written by Love Hörnquist Åstrand <lha@NetBSD.org>, March 2003.
 * Public domain.
 */

#include <sys/types.h>
#include <sys/wait.h>

#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>

static pid_t parent;
static int thread_survived = 0;

static void *
print_pid(void *arg)
{
	sleep(3);

	thread_survived = 1;
	if (parent != getpid()) {
		kill(parent, SIGKILL);
		errx(1, "child thread running");
	}
	return NULL;
}

int
main(int argc, char **argv)
{
	pthread_t p;
	pid_t fork_pid;
	int ret;
	
	parent = getpid();
	
	pthread_create(&p, NULL, print_pid, NULL);

	fork_pid = fork();
	if (fork_pid == -1)
		err(1, "fork failed");
    
	if (fork_pid) {
		ret = pthread_join(p, NULL);
		if (ret && fork_pid != 0)
			errx(1, "join failed in parent");

		if (!thread_survived)
			errx(1, "child_thread did NOT survive");

		if (fork_pid != 0) {
			int status;
			waitpid(fork_pid, &status, 0);
			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
				errx(1, "child died wrongly");
		}
	} else {
		sleep(5);

		if (thread_survived) {
			kill(parent, SIGKILL);
			errx(1, "child_thread survived");
		}
	}

	return 0;
}