Skip to content

Instantly share code, notes, and snippets.

@KJTsanaktsidis
Created May 31, 2023 06:15
Show Gist options
  • Save KJTsanaktsidis/fc84b006cfff1bb0b55a2571df825d80 to your computer and use it in GitHub Desktop.
Save KJTsanaktsidis/fc84b006cfff1bb0b55a2571df825d80 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
void sighandler(int sig) { };
int main(int argc, char **argv) {
char *fifoname = tmpnam(NULL);
int r = mkfifo(fifoname, 0);
if (r == -1) {
perror("mkfifo");
exit(1);
}
printf("fifo: %s\n", fifoname);
chmod(fifoname, 0777);
sigset_t usr1set;
sigemptyset(&usr1set);
sigaddset(&usr1set, SIGUSR1);
sigprocmask(SIG_BLOCK, &usr1set, NULL);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
}
if (pid == 0) {
/* child */
void *s = signal(SIGUSR1, sighandler);
if (s == SIG_ERR) {
perror("signal (child)");
exit(1);
}
printf("opening (child)\n");
sigprocmask(SIG_UNBLOCK, &usr1set, NULL);
int fd;
while ((fd = open(fifoname, O_RDONLY)) == -1) {
if (errno != EINTR) {
perror("open (child)");
exit(1);
}
printf("EINTR on open\n");
}
printf("opened fd %d\n", fd);
char buf[3];
readagain:
r = read(fd, buf, 2);
if (r == -1) {
if (errno == EINTR) {
goto readagain;
}
perror("read (child)");
exit(1);
}
buf[2] = '\0';
printf("%s\n", buf);
exit(0);
} else {
printf("parent\n");
signal(SIGPIPE, SIG_IGN);
for (int i = 0; i < 3; i++) {
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = 1000000000;
nanosleep(&tm, NULL);
kill(pid, SIGUSR1);
}
int fd = open(fifoname, O_WRONLY);
if (fd == -1) {
perror("open (parnet)");
exit(1);
}
char buf[3] = "gg";
printf("parent writing to fd %d\n", fd);
r = write(fd, buf, 2);
if (r == -1) {
perror("write (parent)");
exit(1);
}
printf("exiting ok from parent\n");
exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment