Advertisement
EBobkunov

ex1, 2 w5

Oct 9th, 2023
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 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 <number of subscribers>\n", argv[0]);
  14.         exit(EXIT_FAILURE);
  15.     }
  16.  
  17.     int num_subscribers = atoi(argv[1]);
  18.     int pipe_fds[num_subscribers];
  19.     char pipe_names[num_subscribers][20]; // "/tmp/ex1/sX" where X is the subscriber index
  20.     char message[MAX_MESSAGE_SIZE];
  21.  
  22.     // Create named pipes for each subscriber
  23.     for (int i = 1; i <= num_subscribers; i++) {
  24.         snprintf(pipe_names[i - 1], sizeof(pipe_names[i - 1]), "/tmp/ex1/s%d", i);
  25.         mkfifo(pipe_names[i - 1], 0666);
  26.     }
  27.  
  28.     while (1) {
  29.         // Read a message from stdin
  30.         ssize_t bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE);
  31.  
  32.         if (bytes_read <= 0) {
  33.             break; // Exit if stdin is closed or an error occurs
  34.         }
  35.  
  36.         // Publish the message to all subscribers
  37.         for (int i = 0; i < num_subscribers; i++) {
  38.             pipe_fds[i] = open(pipe_names[i], O_WRONLY);
  39.             write(pipe_fds[i], message, bytes_read);
  40.             close(pipe_fds[i]);
  41.         }
  42.     }
  43.  
  44.     // Cleanup: Close and unlink named pipes
  45.     for (int i = 0; i < num_subscribers; i++) {
  46.         unlink(pipe_names[i]);
  47.     }
  48.  
  49.     return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement