The goal of this lab is to introduce you to some of the UNIX system calls, and also to give you insight into how shell programs like bash or csh are implemented. The assignment is designed to help you understand the functions of fork/exec and the techniques for inter-process communication, such as pipes.
In this lab, you will implement a program that will emulate a command of the form cat <arg1>| grep <arg2> | wc, where arg1 and arg2 are two arguments passed to your program at command line. (Make sure to check you are passed two and only two arguments; otherwise, print an error message and exit.) The output of your program must exactly match with the output of the shell when you type this command at the same prompt. You will have to create your own .c source file, as well as a Makefile which must produce a binary (i.e., executable file) named cgw when make is typed.
As a first step, you will need to duplicate the file handles for stdin and stdout using the dup call. Before a call to fork is made you need to create a pipe and attach one end to the output of one process, and the other end to the input for the next process. When a child process starts to execute (fork returns a pid of 0), you will have to close the open file descriptors. After that you can execute a binary (e.g., cat, grep, or wc), using execlp in the child process. Since you need to make a chain of three processes connected by a pipeline you will have to use two pipes to link them up. You will have to use the dup2() function to redirect input or output.
printf("failed to make a pipe\n");}
exit(1);
close(fdpipe[0]);}
close(fdpipe[1]);
close(defin);
close(defout);
execlp(some program, some program, argument1, argument2, ..., 0);
More information on the fork, execlp, dup, dup2, pipe, open, close, and waitpid functions can be found in their respective man pages, and in the Stevens book (chapters 3, 8, and 14) available on reserve at the math library. Also see the link on the class web page (under "Some Links" near the bottom of the page) for more information on dup() and dup2(). Note that you should not use the "system" function in your code (otherwise, you will receive a score of zero for the lab). Also, make sure NOT to print any extra output when the input is valid: the only output should be the output from "wc."