Question: uses pipes and fork() call to implement the shell pipe |. The code is following: //This program executes ls -ltr | grep 33340, by dividing

uses pipes and fork() call to implement the shell pipe |. The code is following:

//This program executes "ls -ltr | grep 33340", by dividing the two command among the child and parent process

#include

#include

#include

#include

#include

#include

int main(int argc, char **argv) {

int status;

int childpid;

char *cat_args[] = {"ls", "-ltr", NULL};

char *grep_args[] = {"grep", "3340", NULL};

// create one pipe to send the output of "ls" process to "grep" process

int pipes[2]; pipe(pipes);

// fork the first child (to execute cat)

if((childpid = fork()) == -1){

perror("Error creating a child process");

exit(1);

}

if (childpid == 0) {

// replace cat's stdout with write part of 1st pipe

dup2(pipes[1], 1);

// close all pipes (very important!); end we're using was safely copied

close(pipes[0]);

close(pipes[1]);

execvp(*cat_args, cat_args);

exit(0);

}

else {

// replace grep's stdin with read end of 1st pipe

dup2(pipes[0], 0);

close(pipes[0]);

close(pipes[1]);

execvp(*grep_args, grep_args);

}

return(0);

}

Change code to execute the following double pipe command: ls -ltr | grep 3376 | wc l

1- Use one parent and two children to do the work. Call the file TwoPipesTwoChildren.cpp.

2- Write another version where the parent create 3 children, and the children will execute the commands (parent will do nothing, just lay in the sofa ! ). Call the file TwoPipesThreeChildren.cpp

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!