Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- #define MAX_MESSAGE_SIZE 1024
- int main(int argc, char *argv[]) {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <number of subscribers>\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- int num_subscribers = atoi(argv[1]);
- int pipe_fds[num_subscribers];
- char pipe_names[num_subscribers][20]; // "/tmp/ex1/sX" where X is the subscriber index
- char message[MAX_MESSAGE_SIZE];
- // Create named pipes for each subscriber
- for (int i = 1; i <= num_subscribers; i++) {
- snprintf(pipe_names[i - 1], sizeof(pipe_names[i - 1]), "/tmp/ex1/s%d", i);
- mkfifo(pipe_names[i - 1], 0666);
- }
- while (1) {
- // Read a message from stdin
- ssize_t bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE);
- if (bytes_read <= 0) {
- break; // Exit if stdin is closed or an error occurs
- }
- // Publish the message to all subscribers
- for (int i = 0; i < num_subscribers; i++) {
- pipe_fds[i] = open(pipe_names[i], O_WRONLY);
- write(pipe_fds[i], message, bytes_read);
- close(pipe_fds[i]);
- }
- }
- // Cleanup: Close and unlink named pipes
- for (int i = 0; i < num_subscribers; i++) {
- unlink(pipe_names[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement