Pipes
-
Conceptually, a pipe is a connection between two processes, such that
the standard output from one process becomes the standard input
of the other process
-
It is possible to have a series of processes arranged in a
a pipeline, with a pipe between each pair of processes in
the series.
-
Implementation:
A pipe can be implemented as a 10k buffer in main memory with
2 pointers, one for the FROM process and one for TO
process
-
One process cannot read from the buffer until another has written to it
-
The UNIX command-line interpreter (e.g., csh) provide a pipe facility.
-
% prog | more
-
This command runs the prog1 program and send its output to the more
program.
Pipe System Call
-
pipe() is a system call that facilitates inter-process communication.
It opens a pipe, which is an area of main memory that is treated
as a "virtual file". The pipe can be used by the creating process,
as well as all its child processes, for reading and writing.
-
One process can write to this "virtual file" or pipe and another related
process can read from it.
-
If a process tries to read before something is written to the pipe,
the process is suspended until something is written.
-
The pipe system call finds the first two available positions in
the process's open file table and allocates them for the read and
write ends of the pipe. Recall that the open system call allocates
only one position in the open file table.
Syntax in a C/C++ program:
#include <unistd.h>
int pip[2];
(void) pipe(pip);
With error checking:
#include <unistd.h>
int pip[2];
int result;
result = pipe(pip);
if (result == -1)
{
perror("pipe");
exit(1);
}
Programming notes:
-
The pipe() system call is passed a pointer to the beginning of
an array of two integers.
-
It appears in C/C++ as if pipe() is passed the name of the array
without any brackets.
-
The system call places two integers into this array.
These integers are the file descriptors of the first two available
locations in the open file table.
-
pip[0] -
the read end of the pipe -
is a file descriptor used to read from the pipe
-
pip[1] -
the write end of the pipe -
is a file descriptor used to write to the pipe
The buffer size for the pipe is fixed.
Once it is full all further writes are blocked.
Pipes work on a first in first out basis.
Brief Example
-
no error checking, no closing of pipe
#include <unistd.h>
int main()
{
int pid, pip[2];
char instring[20];
pipe(pip);
pid = fork();
if (pid == 0) /* child : sends message to parent*/
{
/* send 7 characters in the string, including end-of-string */
write(pip[1], "Hi Mom!", 7);
}
else /* parent : receives message from child */
{
/* read from the pipe */
read(pip[0], instring, 7);
}
}
Full Example:
Source code for pipe.cpp
( pipe-cpp.txt)
Output for pipe.cpp
Table of Contents