Skip to content

Instantly share code, notes, and snippets.

@alherd-by
Created April 14, 2016 12:21
Show Gist options
  • Save alherd-by/a7d69393dc661f68ff0821f4ae4a675f to your computer and use it in GitHub Desktop.
Save alherd-by/a7d69393dc661f68ff0821f4ae4a675f to your computer and use it in GitHub Desktop.
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <stdbool.h>
#define SEMAPHORE_NAME "/super_sem"
int main(int argc, char **argv) {
int i, count = 0;
sem_t *sem;
int fd[2], nbytes;
char readbuffer[80];
char string[] = "";
pid_t child_pid;
pipe(fd);
if ((sem = sem_open(SEMAPHORE_NAME, O_CREAT, 0777, 0)) == SEM_FAILED) {
perror("sem_open");
return 1;
}
if (fork() == 0) {
while (true) {
if (sem_wait(sem) < 0)
perror("sem_wait");
usleep(2000000);
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s \n", readbuffer);
usleep(1000000);
sem_post(sem);
}
} else {
while (true) {
scanf("%s", string);
write(fd[1], string, (strlen(string) + 1));
sem_post(sem);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment