two way communication between child and parent processes in C using pipes
Sure! Here is an example of how to implement two-way communication between child and parent processes in C using pipes:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int fd1[2]; // File descriptors for the first pipe (parent to child)
int fd2[2]; // File descriptors for the second pipe (child to parent)
char parent_message[] = "Hello child!"; // Message from parent to child
char child_message[] = "Hello parent!"; // Message from child to parent
char buffer[100]; // Buffer to store messages
if (pipe(fd1) == -1 || pipe(fd2) == -1) {
perror("Pipe failed");
exit(1);
}
pid_t pid = fork(); // Create a child process
if (pid < 0) {
perror("Fork failed");
exit(1);
}
if (pid > 0) {
// Parent process
close(fd1[0]); // Close the reading end of the first pipe
close(fd2[1]); // Close the writing end of the second pipe
// Write message from parent to child
write(fd1[1], parent_message, sizeof(parent_message) + 1);
// Read message from child
read(fd2[0], buffer, sizeof(buffer));
printf("Parent received: %s\n", buffer);
close(fd1[1]); // Close the writing end of the first pipe
close(fd2[0]); // Close the reading end of the second pipe
} else {
// Child process
close(fd1[1]); // Close the writing end of the first pipe
close(fd2[0]); // Close the reading end of the second pipe
// Read message from parent
read(fd1[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
// Write message from child to parent
write(fd2[1], child_message, sizeof(child_message) + 1);
close(fd1[0]); // Close the reading end of the first pipe
close(fd2[1]); // Close the writing end of the second pipe
}
return 0;
}
This code demonstrates how to create two pipes, fd1
and fd2
, for communication between the parent and child processes. The pipe()
function is used to create the pipes, and the fork()
function is used to create a child process.
In the parent process, the reading end of fd1
and the writing end of fd2
are closed, as the parent will be writing to fd1
and reading from fd2
. The parent then writes the message parent_message
to fd1
using the write()
function. It then reads the message from the child process by calling read()
on fd2
, and stores the message in the buffer
variable. Finally, the parent closes the writing end of fd1
and the reading end of fd2
.
In the child process, the writing end of fd1
and the reading end of fd2
are closed, as the child will be reading from fd1
and writing to fd2
. The child reads the message from the parent process by calling read()
on fd1
, and stores the message in the buffer
variable. It then writes the message child_message
to fd2
using the write()
function. Finally, the child closes the reading end of fd1
and the writing end of fd2
.
This allows for two-way communication between the parent and child processes using pipes. The parent can send messages to the child, and the child can send messages back to the parent.