Pipe uses kernel buffer to store data. It is a unidirectional read/write buffer and connects two processes. Each end (read or write) Pipe mimics a file operation. A process can choose to read or write (but not both). The processes have to use at least two pipes for two-way communication.
Example Communication
- Parent process can talk to a child with an EOF. Just close its write end of the pipe. The child would get EOF on reading.
Example
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <assert.h>
int main()
{
int contact[2];
pipe(contact);
int fd = fork();
if (fd == 0) { // child
char c;
close(contact[1]); // close the write end.
while (read(contact[0], &c, 1) > 0) // each call checks for EOF.
printf("c=%c", c);
close(contact[0]);
exit(0);
} else { // parent
close(contact[0]); // close the read end.
write(contact[1], "X", 1);
close(contact[1]); // child sees EOF
wait(NULL);
exit(EXIT_SUCCESS);
}
return 1;
}
References
- http://man7.org/linux/man-pages/man2/pipe.2.html
- https://blog.yadutaf.fr/2013/12/28/introduction-to-linux-namespaces-part-2-ipc/
Written with StackEdit.