Advertisement
EBobkunov

publisher.c

Oct 8th, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <string.h>
  6.  
  7. #define MAX_SUBSCRIBERS 3
  8. #define MAX_MESSAGE_SIZE 1024
  9.  
  10. int main(int argc, char* argv[]) {
  11.     if (argc != 2) {
  12.         fprintf(stderr, "Usage: %s <num_subscribers>\n", argv[0]);
  13.         exit(EXIT_FAILURE);
  14.     }
  15.  
  16.     int num_subscribers = atoi(argv[1]);
  17.     if (num_subscribers <= 0 || num_subscribers > MAX_SUBSCRIBERS) {
  18.         fprintf(stderr, "Invalid number of subscribers (1 to %d allowed).\n", MAX_SUBSCRIBERS);
  19.         exit(EXIT_FAILURE);
  20.     }
  21.  
  22.     char fifo_path[20];
  23.     int i;
  24.  
  25.     // Create named pipes for each subscriber
  26.     for (i = 1; i <= num_subscribers; i++) {
  27.         snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
  28.         mkfifo(fifo_path, 0666);
  29.     }
  30.  
  31.     char message[MAX_MESSAGE_SIZE];
  32.     ssize_t bytes_read;
  33.     int pipe_fd;
  34.  
  35.     // Read messages from stdin and send to respective subscribers
  36.     while ((bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE)) > 0) {
  37.         for (i = 1; i <= num_subscribers; i++) {
  38.             snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
  39.             pipe_fd = open(fifo_path, O_WRONLY);
  40.             if (pipe_fd != -1) {
  41.                 write(pipe_fd, message, bytes_read);
  42.                 close(pipe_fd);
  43.             }
  44.         }
  45.     }
  46.  
  47.     // Close and remove named pipes
  48.     for (i = 1; i <= num_subscribers; i++) {
  49.         snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
  50.         unlink(fifo_path);
  51.     }
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement