Advertisement
EBobkunov

ex1.1 w5

Oct 9th, 2023
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5.  
  6. #define MAX_MESSAGE_SIZE 1024
  7.  
  8. int main() {
  9.     int pipe_fd[2]; // File descriptors for the pipe
  10.     pid_t child_pid;
  11.  
  12.     if (pipe(pipe_fd) == -1) {
  13.         perror("Pipe creation failed");
  14.         exit(EXIT_FAILURE);
  15.     }
  16.  
  17.     // Create a child process
  18.     child_pid = fork();
  19.  
  20.     if (child_pid == -1) {
  21.         perror("Fork failed");
  22.         exit(EXIT_FAILURE);
  23.     }
  24.  
  25.     if (child_pid == 0) {
  26.         // This is the subscriber process
  27.         close(pipe_fd[1]); // Close the write end of the pipe
  28.  
  29.         char message[MAX_MESSAGE_SIZE];
  30.         int bytes_read;
  31.  
  32.         while ((bytes_read = read(pipe_fd[0], message, MAX_MESSAGE_SIZE)) > 0) {
  33.             write(STDOUT_FILENO, message, bytes_read); // Print the message to stdout
  34.         }
  35.  
  36.         close(pipe_fd[0]);
  37.     } else {
  38.         // This is the publisher process
  39.         close(pipe_fd[0]); // Close the read end of the pipe
  40.  
  41.         char message[MAX_MESSAGE_SIZE];
  42.         int bytes_read;
  43.  
  44.         while (1) {
  45.             // Read a message from stdin
  46.             bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE);
  47.  
  48.             if (bytes_read <= 0) {
  49.                 break; // Exit if stdin is closed or an error occurs
  50.             }
  51.  
  52.             // Write the message to the pipe
  53.             write(pipe_fd[1], message, bytes_read);
  54.         }
  55.  
  56.         close(pipe_fd[1]); // Close the write end of the pipe
  57.     }
  58.  
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement