From 9f9bcf679e6f627d7bd8b6e21c80906946db65b7 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Thu, 21 Dec 2023 18:34:26 +0100 Subject: Add mmap-race --- c/mmap-race/.gitignore | 1 + c/mmap-race/Makefile | 8 ++++++ c/mmap-race/foo | 1 + c/mmap-race/main.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 c/mmap-race/.gitignore create mode 100644 c/mmap-race/Makefile create mode 100644 c/mmap-race/foo create mode 100644 c/mmap-race/main.c 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 +#include +#include + +#include +#include +#include +#include +#include +#include + +#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); +} -- cgit v1.2.3