Pipes: Pipes Represent A Channel For Interprocess Communication
Pipes: Pipes Represent A Channel For Interprocess Communication
read fd0
write fd1
pipe
flow of data
Initial State of Pipe
Writing process Reading process
pipe
p0
p1
write System Call
Function:
• To write nbytes to the write end of a pipe.
– If a write process attempts to write to a full pipe, the default action is
for the system to block the process until the data is able to be
received.
• Include(s): <unistd.h>
• Syntax: ssize_t write (int fd, const void *buf, size_t nbytes);
– just the write system call
• Returns
– success: Number of bytes written; Failure; -1; Sets errno:Yes.
• Arguments
– int fd: file descriptor;
– const void *buf: buffer;
– size_t nbyte: number of bytes in buffer
read System Call
Function:
• To read nbytes from the read end of a pipe.
– if read is attempted on an empty pipe, the process will block until data
is available.
• Includes: <unistd.h> <sys/types.h> <sys/uio.h>
• Syntax: ssize_t read(int fd, const void *buf, size_t nbytes);
• Return
– success: Number of bytes read;
– Failure; -1; Sets errno:Yes.
– EOF (0): write end of pipe closed
• Arguments
– int fildes: file descriptor;
– const void *buf: buffer;
– size_t nbyte: number of bytes
Unnamed Pipes
• Unnamed pipes can only be used
between related process, such as
parent/child, or child/child process.
• Unnamed pipes can exist only as long as
the processes using them.
• An unnamed pipe is constructed with the
pipe system call.
– See the popen command for an automated
method of using unnamed pipes
• Demo: popenDemo.cpp
Named Pipes
• When generated, named pipes have a directory
entry.
• With the directory entry are file access permissions
and capability for unrelated processes to use the
pipe file.
• Problem: Processes using the pipe know nothing
about each other
– Why is this a problem??
• Named pipes can be created at the shell level or
within a program.
• See mknod or mkfifo commands
Redirecting Standard I/O
A process that communicates solely with
another process doesn’t use its standard I/O.
• If process communicates with another
process only via pipes, redirect standard I/O
to the pipe ends
• Functions: dup, dup2
dup & dup2
#include <unistd.h>
int dup(int fildes);
• Returns a new file descriptor that is a copy of
filedes
• File descriptor returned is first available file
descriptor in file table.
• For example, to dup a read pipe end to stdin (0),
close stdin, then immediately dup the pipe’s read
end.
• Close unused file descriptors; a process should
have only one file descriptor open on a pipe end.
dup & dup2
#include <unistd.h>
int dup2(int fromFD,int toFD);
• Duplicate fromFD to toFD. If toFD is
open, it is closed first.
• For example, if a pipe’s ends are in array
pipefd, dup2(pipefd[1],1) redirects stdout to
the write end of the pipe.
• You still must close the unused pipe end, in
this case pipefd[1]