aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Voss <mail@thomasvoss.com> 2023-12-21 18:34:26 +0100
committerThomas Voss <mail@thomasvoss.com> 2023-12-21 18:34:26 +0100
commit9f9bcf679e6f627d7bd8b6e21c80906946db65b7 (patch)
tree915ac8c03d9ed509bbfd6fa550ce807cccf5c13b
parent2fb71458d07f4ddc6f04773ae75341300fda8905 (diff)
Add mmap-race
-rw-r--r--c/mmap-race/.gitignore1
-rw-r--r--c/mmap-race/Makefile8
-rw-r--r--c/mmap-race/foo1
-rw-r--r--c/mmap-race/main.c67
4 files changed, 77 insertions, 0 deletions
diff --git a/c/mmap-race/.gitignore b/c/mmap-race/.gitignore
new file mode 100644
index 0000000..2b7e469
--- /dev/null
+++ b/c/mmap-race/.gitignore
@@ -0,0 +1 @@
+mmap-race
diff --git a/c/mmap-race/Makefile b/c/mmap-race/Makefile
new file mode 100644
index 0000000..364bf5e
--- /dev/null
+++ b/c/mmap-race/Makefile
@@ -0,0 +1,8 @@
+include ../base.mk
+
+all: mmap-race
+mmap-race: main.c
+ $(CC) $(CFLAGS) -o $@ $<
+
+clean:
+ rm -f mmap-race
diff --git a/c/mmap-race/foo b/c/mmap-race/foo
new file mode 100644
index 0000000..4b5fa63
--- /dev/null
+++ b/c/mmap-race/foo
@@ -0,0 +1 @@
+hello, world
diff --git a/c/mmap-race/main.c b/c/mmap-race/main.c
new file mode 100644
index 0000000..d809688
--- /dev/null
+++ b/c/mmap-race/main.c
@@ -0,0 +1,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);
+}