Cover Image for C Program to Demonstrate fork() and pipe()
162 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:

  1. We create a pipe using the pipe() system call. The pipefd array holds two file descriptors: pipefd[0] for reading and pipefd[1] for writing.
  2. 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.
  3. 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 using read().
  4. 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 using write().
  5. 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS