Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <string.h>
- #define MAX_SUBSCRIBERS 3
- #define MAX_MESSAGE_SIZE 1024
- int main(int argc, char* argv[]) {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <num_subscribers>\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- int num_subscribers = atoi(argv[1]);
- if (num_subscribers <= 0 || num_subscribers > MAX_SUBSCRIBERS) {
- fprintf(stderr, "Invalid number of subscribers (1 to %d allowed).\n", MAX_SUBSCRIBERS);
- exit(EXIT_FAILURE);
- }
- char fifo_path[20];
- int i;
- // Create named pipes for each subscriber
- for (i = 1; i <= num_subscribers; i++) {
- snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
- mkfifo(fifo_path, 0666);
- }
- char message[MAX_MESSAGE_SIZE];
- ssize_t bytes_read;
- int pipe_fd;
- // Read messages from stdin and send to respective subscribers
- while ((bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE)) > 0) {
- for (i = 1; i <= num_subscribers; i++) {
- snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
- pipe_fd = open(fifo_path, O_WRONLY);
- if (pipe_fd != -1) {
- write(pipe_fd, message, bytes_read);
- close(pipe_fd);
- }
- }
- }
- // Close and remove named pipes
- for (i = 1; i <= num_subscribers; i++) {
- snprintf(fifo_path, sizeof(fifo_path), "/tmp/ex1/s%d", i);
- unlink(fifo_path);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement