What do you see when you execute \"pipe1\" ? Why? Modify the program pipe1.cpp t
ID: 3713553 • Letter: W
Question
What do you see when you execute "pipe1" ? Why?
Modify the program pipe1.cpp to pipe1a.cpp so that it accepts a command (e.g. "ls -l") from the keyboard. For example, when you execute "./pipe1a ps -auxw", it should give you the same output as pipe1.cpp.
(Hint: Use string functions strcpy() and strcat() to store the commands in a buffer. Your main function should be like: int main( int argc, char *argv[] ) )
You can also send output to an external program via a pipe. Try the following program:
What do you see when you execute "pipe2" ? Why?
Modify the program so that it prints out the first three words of the sentence in reverse by making use of awk (see lab 2) (i.e. 'If said, Arnod....).
//pipe1.cpp #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <iostream> using namespace std; int main() { FILE *fpi; //for reading a pipe char buffer[BUFSIZ+1]; //BUFSIZ defined in <stdio.h> int chars_read; memset ( buffer, 0,sizeof(buffer)); //clear buffer fpi = popen ( "ps -auxw", "r" ); //pipe to command "ps -auxw" if ( fpi != NULL ) { //read data from pipe into buffer chars_read = fread(buffer, sizeof(char), BUFSIZ, fpi ); if ( chars_read > 0 ) cout << "Output from pipe: " << buffer << endl; pclose ( fpi ); //close the pipe return 0; } return 1; }
Explanation / Answer
What do you see when you execute "pipe1" ? Why??
The pipe1 will execute the command ps as the command is passed to the process. using popen().
And the modified version of the same which takes the parameters dynamically is:
//pipe1.cpp
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main( int argc, char *argv[] )
{
FILE *fpi; //for reading a pipe
char buffer[BUFSIZ+1]; //BUFSIZ defined in <stdio.h>
int chars_read;
strcpy(buffer, argv[1]); //Copies the first parameter to buffer.
for(int i = 2; i < argc; i++) //Copies all the remaining parameters with space appended.
{
strcat(buffer, " ");
strcat(buffer, argv[i]);
}
//cout << buffer << endl;
fpi = popen ( buffer, "r" ); //pipe to command "ps -auxw"
memset ( buffer, 0,sizeof(buffer)); //clear buffer
if ( fpi != NULL ) {
//read data from pipe into buffer
chars_read = fread(buffer, sizeof(char), BUFSIZ, fpi );
if ( chars_read > 0 )
cout << "Output from pipe: " << buffer << endl;
pclose ( fpi ); //close the pipe
return 0;
}
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.