Skip to content

Instantly share code, notes, and snippets.

@jubnzv
Last active December 9, 2018 09:10
Show Gist options
  • Save jubnzv/589ca412df5211d28f587b4bf2dc4ca8 to your computer and use it in GitHub Desktop.
Save jubnzv/589ca412df5211d28f587b4bf2dc4ca8 to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define SIG_SYNC SIGUSR1
uint32_t *Cnt = 0;
void sig_sync_handler(int sig)
{
}
int main(int argc, char const* argv[])
{
int shm_fd;
pid_t pid;
struct sigaction sa;
sigset_t block_mask, empty_mask;
setbuf(stdout, NULL);
sa.sa_flags = 0;
sa.sa_handler = sig_sync_handler;
sigaction(SIG_SYNC, &sa, NULL);
sigemptyset(&empty_mask);
sigemptyset(&block_mask);
sigaddset(&block_mask, SIG_SYNC);
sigprocmask(SIG_BLOCK, &block_mask, NULL);
// Open shm with Cnt
shm_fd = shm_open("/3_11_shm", O_CREAT | O_RDWR, 0600);
ftruncate(shm_fd, sizeof(Cnt));
Cnt = (uint32_t *)mmap(NULL, sizeof(Cnt), PROT_READ | PROT_WRITE,
MAP_SHARED, shm_fd, 0);
*Cnt = 0;
switch (pid = fork()) {
// Child prints even numbers
case 0: {
pid_t ppid = getppid();
for (;;) {
sigsuspend(&empty_mask);
*Cnt += 1;
printf("[Child ]: Cnt=%d\n", *Cnt);
kill(ppid, SIG_SYNC);
}
_exit(EXIT_SUCCESS);
}
default: {
// Parent prints odd numbers
while (*Cnt < 10) {
*Cnt += 1;
printf("[Parent]: Cnt=%d\n", *Cnt);
kill(pid, SIG_SYNC);
sigsuspend(&empty_mask);
}
kill(pid, SIGTERM);
int status;
wait(&status);
exit(EXIT_SUCCESS);
}
case -1:
perror("fork");
exit(EXIT_FAILURE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment