IPC pipe
Thu Jun 06 2024 00:44:36 GMT+0000 (Coordinated Universal Time)
Saved by
@login
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 100
int main() {
int fd[2]; // File descriptors for the pipe
pid_t pid;
char write_msg[BUFFER_SIZE] = "Hello from parent process!";
char read_msg[BUFFER_SIZE];
// Create the pipe
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Fork a child process
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) { // Parent process
close(fd[0]); // Close the read end of the pipe
// Write to the pipe
write(fd[1], write_msg, strlen(write_msg) + 1);
close(fd[1]); // Close the write end of the pipe
} else { // Child process
close(fd[1]); // Close the write end of the pipe
// Read from the pipe
read(fd[0], read_msg, BUFFER_SIZE);
printf("Child process received message: %s\n", read_msg);
close(fd[0]); // Close the read end of the pipe
}
return 0;
}
content_copyCOPY
Comments