ipc pipes

PHOTO EMBED

Fri Jun 07 2024 04:57:31 GMT+0000 (Coordinated Universal Time)

Saved by @prabhas

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main() {
    int fd[2]; // Array to hold the two ends of the pipe: fd[0] for reading, fd[1] for writing
    pid_t pid;
    char writeMessage[] = "Hello from parent process!";
    char readMessage[100];

    // Create the pipe
    if (pipe(fd) == -1) {
        perror("pipe failed");
        return 1;
    }

    // Fork a child process
    pid = fork();

    if (pid < 0) {
        perror("fork failed");
        return 1;
    } else if (pid > 0) {
        // Parent process
        close(fd[0]); // Close the reading end of the pipe in the parent

        // Write a message to the pipe
        write(fd[1], writeMessage, strlen(writeMessage) + 1);
        close(fd[1]); // Close the writing end of the pipe after writing

        // Wait for child process to finish
        wait(NULL);
    } else {
        // Child process
        close(fd[1]); // Close the writing end of the pipe in the child

        // Read the message from the pipe
        read(fd[0], readMessage, sizeof(readMessage));
        printf("Child process received: %s\n", readMessage);
        close(fd[0]); // Close the reading end of the pipe after reading
    }

return 0;
}
content_copyCOPY