Wednesday 5 August 2015

linux 10 program theory

PipesPipes are used to allow one or more processes to have information “flow” between them. The most common example of this is with the shell.

$ ls | wc –l
As we’ve seen the std-out from the left side (ls) is connected to the std-in on the right side (wc -l).As far the each program is concerned, it is reading or writing as it normally does. Both processes are running concurrently.

There are 2 types of pipes:
unnamed pipes
named pipes

The examples we seen at the shell command line are unnamed. They are created, used and destroyed within the life a set of processes. Each end of the pipe has it’s own file descriptor. One end is for reading and one end is for writing. When you are done with a pipe, it is closed like any other file.

Creating unnamed pipes

#include <unistd.h>

int pipe(int fd[2]);

Returns 2 file descriptors in the fd array.

fd[0] is for read

fd[1] write

Returns 0 on successful creation of pipe, 1 otherwise.

Each end of the pipe is closed individually using normal close() system call. Pipes are only available the process that creates the pipe and it’s descendants.

Reading from pipes 

When reading from a pipe:
read() will return 0 (end of file) when the write end of the pipe is closed. if write end of the is still open and there is no data, read() will sleep until input become available. if a read() tries to get more data than is currently in pipe, read() will only contain the number of bytes actually read. Subsequent reads will sleep until more data is available.

Writing to pipes
When writing to a pipe:
If read end of pipe is closes, a write() will fail and process will be sent SIGPIPE signal. Default SIGPIPE handler terminates. 

No comments:

Post a Comment