Advertisement
EBobkunov

ex1 w5 p1

Oct 8th, 2023 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6.  
  7. #define MAX_MESSAGE_SIZE 1024
  8.  
  9. int main() {
  10.     int pipe_fd[2];
  11.     pid_t child_pid;
  12.  
  13.     // Create the pipe
  14.     if (pipe(pipe_fd) == -1) {
  15.         perror("Pipe creation failed");
  16.         exit(EXIT_FAILURE);
  17.     }
  18.  
  19.     // Fork a child process
  20.     if ((child_pid = fork()) == -1) {
  21.         perror("Fork failed");
  22.         exit(EXIT_FAILURE);
  23.     }
  24.  
  25.     if (child_pid == 0) {
  26.         // Child process (Subscriber)
  27.         close(pipe_fd[1]); // Close the write end of the pipe (not needed by subscriber)
  28.  
  29.         char message[MAX_MESSAGE_SIZE];
  30.         ssize_t bytes_read;
  31.  
  32.         while ((bytes_read = read(pipe_fd[0], message, MAX_MESSAGE_SIZE)) > 0) {
  33.             // Print the message received from the publisher
  34.             write(STDOUT_FILENO, message, bytes_read);
  35.         }
  36.  
  37.         close(pipe_fd[0]); // Close the read end of the pipe
  38.     } else {
  39.         // Parent process (Publisher)
  40.         close(pipe_fd[0]); // Close the read end of the pipe (not needed by publisher)
  41.  
  42.         char message[MAX_MESSAGE_SIZE];
  43.         ssize_t bytes_read;
  44.  
  45.         while ((bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE)) > 0) {
  46.             // Send the message to the subscriber via the pipe
  47.             write(pipe_fd[1], message, bytes_read);
  48.         }
  49.  
  50.         close(pipe_fd[1]); // Close the write end of the pipe
  51.     }
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement