Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <sys/types.h>
- #define MAX_MESSAGE_SIZE 1024
- int main() {
- int pipe_fd[2];
- pid_t child_pid;
- // Create the pipe
- if (pipe(pipe_fd) == -1) {
- perror("Pipe creation failed");
- exit(EXIT_FAILURE);
- }
- // Fork a child process
- if ((child_pid = fork()) == -1) {
- perror("Fork failed");
- exit(EXIT_FAILURE);
- }
- if (child_pid == 0) {
- // Child process (Subscriber)
- close(pipe_fd[1]); // Close the write end of the pipe (not needed by subscriber)
- char message[MAX_MESSAGE_SIZE];
- ssize_t bytes_read;
- while ((bytes_read = read(pipe_fd[0], message, MAX_MESSAGE_SIZE)) > 0) {
- // Print the message received from the publisher
- write(STDOUT_FILENO, message, bytes_read);
- }
- close(pipe_fd[0]); // Close the read end of the pipe
- } else {
- // Parent process (Publisher)
- close(pipe_fd[0]); // Close the read end of the pipe (not needed by publisher)
- char message[MAX_MESSAGE_SIZE];
- ssize_t bytes_read;
- while ((bytes_read = read(STDIN_FILENO, message, MAX_MESSAGE_SIZE)) > 0) {
- // Send the message to the subscriber via the pipe
- write(pipe_fd[1], message, bytes_read);
- }
- close(pipe_fd[1]); // Close the write end of the pipe
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement