PDF Document
PDF Document
Operating Systems
Spring 2021 -2022
Interprocess communications
(IPC) (2)
1
B.2 Pipes
O Pipes are one of the most ancient, yet simple and useful, IPC
mechanisms provided by UNIX
O They’ve also been available in MS-DOS from the beginning
12
B.2 Pipes and exec()
O We can now do communication either way:
O dup2(fd[0], 0); ; the process’ stdin now comes from fd[0] (read
from pipe)
13
Example
Child process
#include <sys/types.h>
#include <unistd.h> if (!pid)
{ Duplicate stdout
#include <stdio.h>
#include <stdlib.h> dup2(fd[1], 1);
#include <string.h> close(fd[0]);
int main() execl("/bin/date", "date",
Create pipes
{ NULL);
exit(0); Run a command
pid_t pid; Create a buffer
int fd[2];
}
and set to 0 End of child
if (pipe(fd) == -1)
close(fd[1]);
char buffer[64]; process
{
bzero(buffer,64);
perror("pipe()");
if (read(fd[0], buffer, 64) == -1)
exit(1);
{
} Create child perror("read()");
pid = fork(); Read what the
exit(1);
if (pid < 0) child wrote
}
{ fprintf(stdout,"Output from child:
perror("fork()"); %s",buffer);
exit(1); 14
close(fd[0]);
} exit(0);
}