C Program to Demonstrate fork() and pipe()
In the following tutorial, we will understand the implementation of fork() and pipe() in C Programming language.
So, let's get started.
C Program to Demonstrate fork() and pipe():
Create two processes, P1 and P2, using a C program. P1 hands a string to P2 after receiving it. Without utilizing a string function, P2 joins the received string to another string and sends the result back to P1 for printing.
We utilize a fork to generate a child process (). Fork () returns the following information: 0 fail to create child (new) process =0 for child process >0, i.e. the process ID of the child process to the parent process. Parent process will run when >0.
Information may be sent from one process to another using the pipe() function. Since pipe() is unidirectional, two pipes-one for each direction-can be set up to provide two-way communication between processes.
Inside Parent Process: We first close the first pipe's reading end (fd1), then we write the string via the pipe's writing end (fd1). Parent will now wait till the child's process is complete. After the child process, the parent will shut the second pipe's writing end (fd2), and read the string through the pipe's reading end (fd2).
Within the child process, the child reads the first string that the parent process delivered by shutting the writing end of the pipe (fd1), concatenates the two strings after reading them, and then sends the string to the parent process via the fd2 pipe before exiting.