Lab 07
Lab 07
Summary
Items Description
Course Title Operating System
Lab Title Interprocess Communication using Pipes
Duration 3 Hours
Operating System Linux Operating System
/Tool/Language
Objective Implement the Interprocess Communication using pipes
Pipes:
A pipe’s data capacity is limited. If the writer process writes faster than the reader
process consumes the data, and if the pipe cannot store more data, the writer process
blocks until more capacity becomes available. If the reader tries to read but no data is
available, it blocks until data becomes available. Thus, the pipe automatically
synchronizes the two processes.
Creating Pipes:
To create a pipe, invoke the pipe command. Supply an integer array of size 2.The call
to pipe stores the reading file descriptor in array position 0 and the writing file
descriptor in position 1. For example, consider the code:
int pipe_fds[2];
int read_fd;
int write_fd;
pipe (pipe_fds);
read_fd = pipe_fds[0];
write_fd = pipe_fds[1];
Data written to the file descriptor read_fd can be read back from write_fd.
To create a simple pipe with C, we make use of the pipe () system call. It takes a
single argument, which is an array of two integers. If successful, the array will contain
two new file descriptors to be used for the pipeline.
NOTE:
o fd[0] is set up for reading
o fd[1] is set up for writing
The first integer in the array (element 0) is set up and opened for reading, while the
second integer (element 1) is set up and opened for writing. Visually speaking, the
output of fd1 becomes the input for fd0.
//Parent creates pipe, forks a child, child writes into pipe, and parent reads from pipe
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
main()
{
int pipefd[2], pid, n, rc, nr, status;
char *testString = "Hello, world!\n";
char buf[1024];
rc = pipe (pipefd);
if (rc < 0)
{
perror("pipe");
}
pid = fork ();
if (pid < 0)
{
perror("fork");
}
if (pid == 0)
{ /* Child’s Code */
close(pipefd[0]);
write(pipefd[1], testString, strlen(testString));
close(pipefd[1]);
}
else /* Parent’s Code */
{
close(pipefd[1]);
n = strlen(testString);
nr = read(pipefd[0], buf, n);
rc = write(1, buf, nr);
wait(&status);
printf("End!\n");
}
return(0);
}
LAB TASKS
Task 1:
Task 2:
o Using pipes, parent read data from one file, and child write data into another
file.