Tobiahao

S01_LAB02_08a

Nov 13th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 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 pierwszy
  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.     if((unlink(SEND_FIFO_DIR) == -1) || (unlink(RECV_FIFO_DIR))){
  32.         perror("unlink");
  33.         exit(EXIT_FAILURE);
  34.     }
  35.  
  36.     printf("\n");
  37.  
  38.     exit(EXIT_SUCCESS);
  39. }
  40.  
  41. int main(void)
  42. {
  43.     char buffer[BUFFER_SIZE];
  44.     bool send_recv_order = true;
  45.  
  46.     if(signal(SIGINT, sigint_handler) == SIG_ERR){
  47.         perror("signal");
  48.         return EXIT_FAILURE;
  49.     }
  50.  
  51.     if((mknod(SEND_FIFO_DIR, S_IFIFO | 0600, 0) == -1) || mknod(RECV_FIFO_DIR, S_IFIFO | 0600, 0)){
  52.         perror("mknod");
  53.         return EXIT_FAILURE;
  54.     }
  55.  
  56.     printf("Oczekiwanie na drugiego uzytkownika...\n");
  57.     if((send_fd = open(SEND_FIFO_DIR, O_WRONLY)) == -1){
  58.         perror("open");
  59.         return EXIT_FAILURE;
  60.     }
  61.     if((recv_fd = open(RECV_FIFO_DIR, O_RDONLY)) == -1){
  62.         perror("open");
  63.         return EXIT_FAILURE;
  64.     }
  65.  
  66.     while(1){
  67.         if(send_recv_order){
  68.             printf("> ");
  69.             memset(buffer, '\0', BUFFER_SIZE);
  70.             fgets(buffer, BUFFER_SIZE, stdin);
  71.  
  72.             if(write(send_fd, buffer, BUFFER_SIZE) == -1){
  73.                 perror("write");
  74.                 return EXIT_FAILURE;
  75.             }
  76.         }
  77.         else{
  78.             memset(buffer, '\0', BUFFER_SIZE);
  79.             if(read(recv_fd, buffer, BUFFER_SIZE) == -1){
  80.                 perror("read");
  81.                 return EXIT_FAILURE;
  82.             }
  83.  
  84.             printf("< %s\n", buffer);
  85.         }
  86.         send_recv_order = !send_recv_order;
  87.     }
  88.  
  89.     if((close(send_fd) == -1) || (close(recv_fd) == -1)){
  90.         perror("close");
  91.         return EXIT_FAILURE;
  92.     }  
  93.  
  94.     return EXIT_SUCCESS;
  95. }
Add Comment
Please, Sign In to add comment