Tobiahao

S01_LAB02_08b

Nov 13th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. /*
  2. Stwórz programy do dialogu mi ę dzy dwoma u ż ytkownikami w systemie. Do
  3. komunikacji u ż yj łą cza FIFO stworzonego za pomoc ą funkcji mknod.
  4. */
  5.  
  6. // Program drugi
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <fcntl.h>
  13. #include <unistd.h>
  14. #include <string.h>
  15. #include <signal.h>
  16. #include <stdbool.h>
  17.  
  18. #define BUFFER_SIZE 256
  19. #define SEND_FIFO_DIR "./send_fifo"
  20. #define RECV_FIFO_DIR "./recv_fifo"
  21.  
  22. int send_fd, recv_fd;
  23.  
  24. void sigint_handler(int signum)
  25. {
  26.     if((close(send_fd) == -1) || (close(recv_fd) == -1)){
  27.         perror("close");
  28.         exit(EXIT_FAILURE);
  29.     }
  30.  
  31.     printf("\n");
  32.     exit(EXIT_SUCCESS);
  33. }
  34.  
  35. int main(void)
  36. {
  37.     char buffer[BUFFER_SIZE];
  38.     bool send_recv_order = false;
  39.  
  40.     if(signal(SIGINT, sigint_handler) == SIG_ERR){
  41.         perror("signal");
  42.         return EXIT_FAILURE;
  43.     }
  44.  
  45.     if((send_fd = open(SEND_FIFO_DIR, O_RDONLY)) == -1){
  46.         perror("open");
  47.         return EXIT_FAILURE;
  48.     }
  49.     if((recv_fd = open(RECV_FIFO_DIR, O_WRONLY)) == -1){
  50.         perror("open");
  51.         return EXIT_FAILURE;
  52.     }
  53.  
  54.     while(1){
  55.         if(send_recv_order){
  56.             printf("> ");
  57.             memset(buffer, '\0', BUFFER_SIZE);
  58.             fgets(buffer, BUFFER_SIZE, stdin);
  59.  
  60.             if(write(recv_fd, buffer, BUFFER_SIZE) == -1){
  61.                 perror("write");
  62.                 return EXIT_FAILURE;
  63.             }
  64.         }
  65.         else{
  66.             memset(buffer, '\0', BUFFER_SIZE);
  67.             if(read(send_fd, buffer, BUFFER_SIZE) == -1){
  68.                 perror("read");
  69.                 return EXIT_FAILURE;
  70.             }
  71.  
  72.             printf("< %s\n", buffer);
  73.         }
  74.         send_recv_order = !send_recv_order;
  75.     }
  76.  
  77.     if((close(send_fd) == -1) || (close(recv_fd) == -1)){
  78.         perror("close");
  79.         return EXIT_FAILURE;
  80.     }  
  81.  
  82.     return EXIT_SUCCESS;
  83. }
Add Comment
Please, Sign In to add comment