xref: /illumos-gate/usr/src/test/libc-tests/tests/random/inz_child.c (revision 440a8a36792bdf9ef51639066aab0b7771ffcab8)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright (c) 2015, Joyent, Inc.
14  */
15 
16 /*
17  * Verify that using MC_INHERIT_ZERO works just fine when applied to an entire
18  * region across multiple children.
19  */
20 
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <assert.h>
24 #include <sys/mman.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <stdlib.h>
28 #include <wait.h>
29 
30 static int nchild = 5;
31 
32 int
33 main(void)
34 {
35 	void *buf;
36 	pid_t child;
37 	int ret, i;
38 	siginfo_t info;
39 	uint8_t *ubuf;
40 	size_t mapsz = sysconf(_SC_PAGESIZE) * 2;
41 
42 	buf = mmap(NULL, mapsz, PROT_READ | PROT_WRITE,
43 	    MAP_PRIVATE | MAP_ANON, -1, 0);
44 	assert(buf != MAP_FAILED);
45 
46 	ret = memcntl(buf, mapsz, MC_INHERIT_ZERO, 0, 0, 0);
47 	assert(ret == 0);
48 
49 again:
50 	memset(buf, 'a' + nchild, mapsz);
51 	child = fork();
52 	if (child == 0) {
53 		nchild--;
54 		for (i = 0, ubuf = buf; i < mapsz; i++)
55 			assert(ubuf[i] == 0);
56 		if (nchild != 0)
57 			goto again;
58 		exit(0);
59 	}
60 	assert(child != -1);
61 
62 	do {
63 		ret = waitid(P_PID, child, &info, WEXITED);
64 	} while (ret == -1 && errno == EINTR);
65 	assert(ret == 0);
66 	assert(info.si_pid == child);
67 	assert(info.si_status == 0);
68 
69 	for (i = 0, ubuf = buf; i < mapsz; i++)
70 		assert(ubuf[i] == 'a' + nchild);
71 
72 	return (0);
73 }
74