UNX511/DSP912 - Lab 7: Pipes Between Processes

Due: Sunday, July 21, 2024

In this lab you will create a program that will take two arguments, with the intention that the output of the first argument will be piped to the second argument. This is done to simulate shell behaviour. Your program will be invoked as follows:
$ ./Lab7 <argument1> <argument2>

<argument1> and <argument2> could be one, two or three strings in length.
If an argument is more than one string in length, it has to be put in quotes.

For instance, say you want to see if any syslog processes are running on your machine, you would type the following from the command line:
$ ps -aux | grep -i syslog

Your program should do the exact same thing if invoked as follows:
$ ./Lab7 "ps -aux" "grep -i syslog"

where <argument1>="ps -aux" and <argument2>="grep -i syslog".

The idea basically is to use pipe() in your code to pipe the output of one process (<argument1>) into the input of the second process (<argument2>) and display the results on the screen.

You may have problems breaking up argument1 and/or argument2 into separate strings. Here is one way to do so:
const int LEN=32;

char argument1[LEN];
char argument2[LEN];
strcpy(argument1, argv[1]);
strcpy(argument2, argv[2]);
char arg1[3][LEN];//max 3 strings
char arg2[3][LEN];//max 3 strings
int len1=0, len2=0;

char *token=strtok(argument1, " ");
while(token!=NULL) {
     strcpy(arg1[len1], token);
     token=strtok(NULL, " ");
     ++len1;
}
token=strtok(argument2, " ");
while(token!=NULL) {
     strcpy(arg2[len2], token);
     token=strtok(NULL, " ");
     ++len2;
}

For assistance on this, please see the video:
Pipe, fork, dup exec explained

In your submission of Lab7.cpp, please answer the following questions in your own words:

  1. How does dup() work?
  2. How does dup2() work?
  3. How does execlp() work?

Lab Submission:

Please embed your answers to the above questions in your Lab7.cpp and mail your Lab7.cpp and Makefile to: shahdad.shariatmadari@senecapolytechnic.ca