Advertisement
EBobkunov

ex1,,3 w5

Oct 9th, 2023
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8.  
  9. #define MAX_MESSAGE_SIZE 1024
  10.  
  11. int main(int argc, char *argv[]) {
  12.     if (argc != 2) {
  13.         fprintf(stderr, "Usage: %s <subscriber index>\n", argv[0]);
  14.         exit(EXIT_FAILURE);
  15.     }
  16.  
  17.     int subscriber_index = atoi(argv[1]);
  18.     char pipe_name[20]; // "/tmp/ex1/sX" where X is the subscriber index
  19.     char message[MAX_MESSAGE_SIZE];
  20.  
  21.     // Create the named pipe filename for this subscriber
  22.     snprintf(pipe_name, sizeof(pipe_name), "/tmp/ex1/s%d", subscriber_index);
  23.  
  24.     int pipe_fd = open(pipe_name, O_RDONLY);
  25.  
  26.     if (pipe_fd == -1) {
  27.         perror("Failed to open the named pipe");
  28.         exit(EXIT_FAILURE);
  29.     }
  30.  
  31.     while (1) {
  32.         ssize_t bytes_read = read(pipe_fd, message, MAX_MESSAGE_SIZE);
  33.  
  34.         if (bytes_read <= 0) {
  35.             break; // Exit if the pipe is closed or an error occurs
  36.         }
  37.  
  38.         write(STDOUT_FILENO, message, bytes_read); // Print the received message
  39.     }
  40.  
  41.     close(pipe_fd);
  42.  
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement