#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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter