From 6834a4c4094d133e771491b134e8da73a9f00a07 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Mon, 24 Mar 2025 21:37:10 +0200 Subject: add mini fork test tool --- tools/forktest.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 tools/forktest.c (limited to 'tools/forktest.c') diff --git a/tools/forktest.c b/tools/forktest.c new file mode 100644 index 0000000..49dc40e --- /dev/null +++ b/tools/forktest.c @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +#include + +int main() { + int fd = open("testfile", O_WRONLY| O_CREAT, 0644); + if (fd < 0) { + perror("open"); + return 1; + } + int flags = fcntl(fd, F_GETFL); + printf("Parent: File access mode is O_RDWR|O_CREAT (%d %d %d)\n", flags, O_RDWR|O_CREAT, O_WRONLY|O_CREAT); + + pid_t pid = fork(); + if (pid < 0) { + perror("fork"); + return 1; + } else if (pid == 0) { // Child process + // Change file access mode + if (fcntl(fd, F_SETFL, O_RDONLY) < 0) { + perror("fcntl"); + return 1; + } + int flags = fcntl(fd, F_GETFL); + printf("Child: Changed file access mode to O_RDONLY|.. (%d)\n", flags); + _exit(0); + } else { // Parent process + sleep(2); + int flags = fcntl(fd, F_GETFL); + if (flags < 0) { + perror("fcntl"); + return 1; + } + if (flags & O_RDONLY) { + printf("Parent: File access mode changed to O_RDONLY|.. (%d)\n", flags); + } else { + printf("Parent: File access mode is still O_RDWR|.. (%d)\n", flags); + } + } + + close(fd); + return 0; +} -- cgit v1.2.3