aboutsummaryrefslogtreecommitdiff
path: root/c/mmap-race/main.c
blob: d8096880d8071777d02cea579aac8db091419602 (plain) (blame)
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
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>

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

#define die(...) err(EXIT_FAILURE, __VA_ARGS__)

static void chld(void);
static void prnt(void);

int
main(void)
{
	pid_t pid;
	switch (pid = fork()) {
	case -1:
		die("fork");
	case 0:
		chld();
		break;
	default:
		prnt();
	}
	return EXIT_SUCCESS;
}

void
chld(void)
{
	int fd;

	sleep(1);
	if ((fd = open("foo", O_WRONLY)) == -1)
		die("open: foo");
	if (write(fd, "overwritten", sizeof("overwritten") - 1) == -1)
		die("write");

	close(fd);
}

void
prnt(void)
{
	int fd;
	char *buf;
	struct stat sb;

	if ((fd = open("foo", O_RDONLY)) == -1)
		die("open: foo");
	if (fstat(fd, &sb) == -1)
		die("fstat: foo");
	if ((buf = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0))
	    == MAP_FAILED)
		die("mmap");

	wait(NULL);
	write(STDOUT_FILENO, buf, sb.st_size);

	munmap(buf, sb.st_size);
	close(fd);
}