Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <semaphore.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <fcntl.h>
- #define BUF_SIZE 512
- const char* read_semaphore = "read_semaphore";
- const char* write_semaphore = "write_semaphore";
- sem_t* open_sem(const char* sem_name)
- {
- sem_t* sem = sem_open(sem_name, 0); // open existing semaphore
- if (sem == SEM_FAILED)
- {
- fprintf(stderr, "Can't create a semaphore\n");
- return NULL;
- }
- return sem;
- }
- sem_t* read_sem = NULL;
- sem_t* write_sem = NULL;
- void sig_handler(int signum)
- {
- sem_close(read_sem);
- sem_close(write_sem);
- exit(EXIT_SUCCESS);
- }
- int main(int argc, char** argv)
- {
- read_sem = open_sem(read_semaphore);
- write_sem = open_sem(write_semaphore);
- struct sigaction act;
- memset(&act, 0, sizeof(struct sigaction));
- act.sa_handler = sig_handler;
- if (sigaction(SIGTERM, &act, NULL) == -1)
- {
- fprintf(stdout, "Sigaction failed\n");
- exit(EXIT_FAILURE);
- }
- char string[BUF_SIZE];
- while (1)
- {
- sem_wait(read_sem);
- read(0, string, BUF_SIZE);
- puts(string);
- sem_post(write_sem);
- }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement