Advertisement
3axap_010

client.c

Apr 16th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <sys/stat.h>
  3. #include <sys/types.h>
  4. #include <semaphore.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <signal.h>
  9. #include <fcntl.h>
  10.  
  11. #define BUF_SIZE 512
  12.  
  13. const char* read_semaphore = "read_semaphore";
  14. const char* write_semaphore = "write_semaphore";
  15.  
  16. sem_t* open_sem(const char* sem_name)
  17. {
  18.     sem_t* sem = sem_open(sem_name, 0); // open existing semaphore
  19.     if (sem == SEM_FAILED)
  20.     {
  21.         fprintf(stderr, "Can't create a semaphore\n");
  22.         return NULL;
  23.     }
  24.  
  25.     return sem;
  26. }
  27.  
  28. sem_t* read_sem = NULL;
  29. sem_t* write_sem = NULL;
  30.  
  31. void sig_handler(int signum)
  32. {
  33.     sem_close(read_sem);
  34.     sem_close(write_sem);
  35.     exit(EXIT_SUCCESS);
  36. }
  37.  
  38. int main(int argc, char** argv)
  39. {
  40.     read_sem = open_sem(read_semaphore);
  41.     write_sem = open_sem(write_semaphore);
  42.    
  43.     struct sigaction act;
  44.     memset(&act, 0, sizeof(struct sigaction));
  45.     act.sa_handler = sig_handler;
  46.  
  47.     if (sigaction(SIGTERM, &act, NULL) == -1)
  48.     {
  49.         fprintf(stdout, "Sigaction failed\n");
  50.         exit(EXIT_FAILURE);
  51.     }
  52.  
  53.     char string[BUF_SIZE];
  54.  
  55.     while (1)
  56.     {
  57.         sem_wait(read_sem);
  58.  
  59.         read(0, string, BUF_SIZE);
  60.         puts(string);
  61.  
  62.         sem_post(write_sem);   
  63.     }
  64.  
  65.     exit(EXIT_SUCCESS);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement