Escolar Documentos
Profissional Documentos
Cultura Documentos
System Programming
Pipes
1
Pipes
#include <unistd.h>
int pipe(int P[2]);
• system call used to create a pipe
¾Where p is a two element integer array
¾P[1]: file descriptor on upstream end of pipe
¾P[0]: file descriptor on downstream end of pipe
P[1] P[0]
Pipes
user process
read fd
write fd
Æflow of data Æ
pipe
2
IPC Using Pipes
Using Pipes
Parent process A
pipe()
Reading process
fork()
Writing process
Close the writing fork()
end of pipe
Close both Close the reading
ends of pipe end of pipe
read() write()
close(…)
wait()
close(…) exit()
wait()
exit()
Continue
or exit
3
Child B Child C Process
write
write fd
fd read
read fd
fd
Kernel
Pipe
Pipe
4
• Closing upstream end of pipe is essential for
1st (reading) process or it will never see EOF.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int fd[2];
if (pipe(fd) == -1)
perror("Failed to create the pipe");
5
Synchronization Using Pipes
Kernel
Flow of Data
Pipe
Pipe
Pipe
Pipe
Flow of Data
6
Redirection
#include <unistd.h>
int dup2(int FileDesc1, int FileDesc2);
• Closes entry FileDesc1 of the file descriptor table if open
• Copies the pointer of entry FileDesc1 into entry FileDesc2
• Returns the file descriptor value that was duplicated
• Example:
fd = open("my.file“,O_RDRW )
dup2(fd,1)
Example
% ls | sort
• The shell gets the output of “ls” connected to the upstream end
of the pipe, and the input to “sort” connected to the
downstream end.
• Shell uses dup2 to do the plumbing:
¾ dup2(old, new):
¾ takes an existing file descriptor (old) and duplicates it into (new
location).
int p[2];
pipe(p);
dup2(p[1], 1);
/*standard output connected upstream end of pipe*/
7
Example
main() {
int fds[2];
pipe(fds);
/*child 1 duplicates downstream into stdin */
if (fork() == 0) {
dup2(fds[0], 0);
close(fds[1]);
execlp(“sort”, “sort”, 0); }
/*child 2 duplicates upstream into stdout */
else if fork() == 0) {
dup2(fds[1], 1);
close(fds[0]);
execlp(“ls”, ”ls”, 0); }
else{ /*parent closes both ends and wait for children*/
close(fds[0]);
close(fds[1]);
wait(0);
wait(0); }
}
Example
8
Characteristics of Pipes
• Unidirectional
• Pipes can only be used between processes that
have a common ancestor (named pipes)
• No mechanism to authenticate
• Do not work across the network
• They are the easiest of IPC mechanisms.
Simple, easy to understand and easy to
implement as well.
Midterm Exam
When: ????
Where: in class
How: Closed book and notes