Pipes can be used in threads and processes. The program below demonstrates how pipes can be used in processes. A new process can be created using the system call fork(). It returns two differnt values to the child and parent. The value 0 is returned to the child (new) process and the PID (Process ID) of the child is returned to the parent process. This is used to distinguish between the two processes. In the program given below, the child process waits for the user input and once an input is entered, it writes into the pipe. And the parent process reads from the pipe.
A sample program to demonstrate how pipes are used in Linux Processes
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MSGLEN 64
int main(){
int fd[2];
pid_t pid;
int result;
//Creating a pipe
result = pipe (fd);
if (result < 0) {
//failure in creating a pipe
perror("pipe");
exit (1);
}
//Creating a child process
pid = fork();
if (pid < 0) {
//failure in creating a child
perror ("fork");
exit(2);
}
if (pid == 0) {
//Child process
char message[MSGLEN];
while(1) {
//Clearing the message
memset (message, 0, sizeof(message));
printf ("Enter a message: ");
scanf ("%s",message);
//Writing message to the pipe
write(fd[1], message, strlen(message));
}
exit (0);
}
else {
//Parent Process
char message[MSGLEN];
while (1) {
//Clearing the message buffer
memset (message, 0, sizeof(message));
//Reading message from the pipe
read (fd[0], message, sizeof(message));
printf("Message entered %s\n",message);
}
exit(0);
}
}
Note here that the pipe() system call was called before the system call fork(). The buffer allocated to the pipe is accessible to both the processes.