
291 views
C Program to Demonstrate fork() and pipe()
The C program that demonstrates the use of the fork()
system call to create a child process and the pipe()
system call to establish interprocess communication (IPC) between the parent and child processes:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
int pipefd[2]; // File descriptors for the pipe
pid_t child_pid;
// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Create a child process
child_pid = fork();
if (child_pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) {
// Child process
// Close the write end of the pipe since it won't be used by the child
close(pipefd[1]);
char message[100];
int bytes_read;
// Read data from the pipe
bytes_read = read(pipefd[0], message, sizeof(message));
if (bytes_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Child Process: Received message from parent: %.*s", bytes_read, message);
// Close the read end of the pipe
close(pipefd[0]);
} else {
// Parent process
// Close the read end of the pipe since it won't be used by the parent
close(pipefd[0]);
char message[] = "Hello from the parent!";
int bytes_written;
// Write data to the pipe
bytes_written = write(pipefd[1], message, strlen(message));
if (bytes_written == -1) {
perror("write");
exit(EXIT_FAILURE);
}
// Close the write end of the pipe
close(pipefd[1]);
}
return 0;
}
In this program:
- We create a pipe using the
pipe()
system call. Thepipefd
array holds two file descriptors:pipefd[0]
for reading andpipefd[1]
for writing. - We fork the process using the
fork()
system call, creating a child process. The child process inherits the open file descriptors from the parent, including the pipe. - In the child process, we close the write end of the pipe (
pipefd[1]
) since it won’t be used by the child. The child then reads data from the pipe usingread()
. - In the parent process, we close the read end of the pipe (
pipefd[0]
) since it won’t be used by the parent. The parent writes a message to the pipe usingwrite()
. - After reading or writing data, both the parent and child processes close the respective ends of the pipe to release system resources.
When you run this program, you’ll see that the child process receives the message sent by the parent process through the pipe. The pipe facilitates communication between the two processes.