Last active
July 26, 2025 18:57
-
-
Save mjkpolo/0327081a3a209129642b3b1ab71fb942 to your computer and use it in GitHub Desktop.
shared memory fork example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdio.h> | |
#include <sys/fcntl.h> | |
#include <sys/mman.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
static volatile bool *running; | |
void handler(int sig) { | |
(void)sig; | |
*running = false; | |
} | |
void do_child_work(void) { | |
while (*running) | |
sleep(1); | |
} | |
const char *shmem_name = "shm_fork_test"; | |
int main(void) { | |
int ret = 0; | |
if (signal(SIGINT, handler) == SIG_IGN) | |
signal(SIGINT, SIG_IGN); | |
if (signal(SIGHUP, handler) == SIG_IGN) | |
signal(SIGHUP, SIG_IGN); | |
if (signal(SIGTERM, handler) == SIG_IGN) | |
signal(SIGTERM, SIG_IGN); | |
int shm_fd = shm_open(shmem_name, O_RDWR | O_CREAT); | |
if (shm_fd == -1) { | |
perror("shm_open"); | |
ret = 1; | |
goto cleanup; | |
} | |
if (ftruncate(shm_fd, sizeof(*running)) == -1) { | |
perror("ftruncate"); | |
ret = 1; | |
goto cleanup; | |
} | |
void *shm = mmap(NULL, sizeof(*running), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); | |
if (shm == MAP_FAILED) { | |
perror("mmap"); | |
ret = 1; | |
goto cleanup; | |
} | |
running = shm; | |
*running = true; | |
#define N_CHILD (8) | |
pid_t pid[N_CHILD]; | |
for (int i = 0; i < N_CHILD; i++) { | |
pid[i] = fork(); | |
if (pid[i] == -1) { | |
perror("fork"); | |
ret = 1; | |
goto cleanup; | |
} else if (pid[i] == 0) { | |
do_child_work(); | |
return 0; | |
} | |
printf("forked child %d\n", pid[i]); | |
} | |
for (pid_t *p = pid; p < pid + N_CHILD; p++) { | |
printf("waiting on %d\n", *p); | |
if (waitpid(*p, NULL, 0) == -1) { | |
perror("wait"); | |
ret = 1; | |
goto cleanup; | |
} | |
} | |
cleanup: | |
printf("cleanup\n"); | |
if (shm_unlink(shmem_name) == -1) { | |
perror("shm_unlink"); | |
ret = 1; | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment