Question: //pipe1.cpp #include #include #include #include #include using namespace std; int main() { FILE *fpi; //for reading a pipe char buffer[BUFSIZ+1]; //BUFSIZ defined in int chars_read;

//pipe1.cpp #include  #include  #include  #include  #include  using namespace std; int main() { FILE *fpi; //for reading a pipe char buffer[BUFSIZ+1]; //BUFSIZ defined in  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; } 

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:

//pipe2.cpp #include  #include  #include  #include  #include  using namespace std; int main() { FILE *fpo; //for writing to a pipe char buffer[BUFSIZ+1]; //BUFSIZ defined in  //Write buffer a message sprintf(buffer, "Arnod said, 'If I am elected, ..', and the fairy tale begins "); fpo = popen ( "od -c", "w" ); //pipe to command "od -c" //od -- output dump, see "man od" if ( fpo != NULL ) { //send data from buffer to pipe fwrite(buffer, sizeof(char), strlen(buffer), fpo ); pclose ( fpo ); //close the pipe return 0; } return 1; } 

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....).

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!