CS360 Final Exam: December 12, 2000. Question 5: Answer and Grading
This is a simple matter of getting the pipe/dup2/close/wait calls
correct. Here is the answer. You could do other things, like making
both pipe() calls initially, or closing everything in the parent
just before the wait() calls, but this is pretty much it:
#include < stdio.h >
#include < fcntl.h >
main()
{
int pa[2];
int pb[2];
int fd;
int dummy;
pipe(pa);
if (fork() == 0) {
fd = open("f1", O_RDONLY);
if (fd < 0) { perror("f1"); exit(1); }
dup2(fd, 0);
dup2(pa[1], 1);
close(fd);
close(pa[0]);
close(pa[1]);
execlp("sort", "sort", NULL);
perror("execlp");
exit(1);
}
close(pa[1]);
pipe(pb);
if (fork() == 0) {
dup2(pa[0], 0);
dup2(pb[1], 1);
close(pa[0]);
close(pb[0]);
close(pb[1]);
execlp("head", "head", "-5", NULL);
perror("execlp");
exit(1);
}
close(pa[0]);
close(pb[1]);
if (fork() == 0) {
dup2(pb[0], 0);
close(pb[0]);
execlp("cat", "cat", "-n", NULL);
perror("execlp");
exit(1);
}
close(pb[0]);
wait(&dummy);
wait(&dummy);
wait(&dummy);
}
Grading
12 points
One point for each of the following:
- Calling the first pipe in the right place
- Opening f1 in the first child
- Dup2'ing f1 and pa[1] in the first child
- Making all the correct closes
- Calling the first pipe in the right place: 1 point
- Dup2'ing pa[0] and pb[1] in the second child
- Making all the correct closes in the second child
- Dup2'ing pb[1] in the third child
- Making all the correct closes in the third child
- Making all the correct closes in the parent
- Calling exit after the execlp calls
- Making the wait calls
I went fractional here -- if you had to make three closes, and you
only made 2, you got 2/3 (0.67). If you didn't check for the
open of f1 failing, you only got 3/4.
Points were deducted for the following reasons:
- Too much extraneous code: 1 to 2 points
- Bad form, even though lots of the calls are right: 1 to 11 points