The second method for IPC is using the pipe() function. Before writing a program for IPC using pipe() function let us first understand its working.
int pipe(int pipefd);
pipe() function creates a unidirectional pipe for IPC. On success it return two file descriptors pipefd and pipefd. pipefd is the reading end of the pipe. So, the process which will receive the data should use this file descriptor. pipefd is the writing end of the pipe. So, the process that wants to send the data should use this file descriptor.
The program below creates a child process. The parent process will establish a pipe and will send the data to the child using writing end of the pipe and the child will receive that data and print on the screen using the reading end of the pipe.
//Q. Program to send a message from parent process to child process using pipe()
pipe(fd); //creates a unidirectional pipe with two end fd and fd
printf("Parent Passing value to child\n");
write(fd,"hello\n",6); //fd is the write end of the pipe
else // child
printf("Child printing received value\n");
n=read(fd,buffer,100); //fd is the read end of the pipe
The parent process create a pipe using pipe(fd) call and then creates a child process using fork(). Then the parent sends the data by writing to the writing end of the pipe by using the fd file descriptor. The child then reads this using the fd file descriptor and stores it in buffer. Then the child prints the received data from the buffer onto the screen.
Q1. Which kind of data channel is created by pipe() system call: Unidirectional or bidirectional?
Q2. What does the pipe() system call return on success?
Q3. What does the pipe() system call return on failure?
Q4. Why fork() is used in the above program?
Q5. Which process (parent or child) in the above code, is using the writing end of the pipe?