Question: Modify this shell function so that it supports pipes between programs. You can assume there will always be spaces around the special character | .

Modify this shell function so that it supports pipes between programs. You can assume there will always be spaces around the special character |.You must support an indefinite number of pipes in series. Code segement here: int pipe_count =0;
int i =0;
int background =0; // Flag to indicate if the command is to be executed in the background
// Check if the command is to be executed in the background
while (args[i]!= NULL){
if (strcmp(args[i],"&")==0){
background =1;
args[i]= NULL; // Remove the '&' token
break;
}
i++;
}
// Count the number of pipes
i =0;
while (args[i]!= NULL){
if (strcmp(args[i],"|")==0){
pipe_count++;
}
i++;
}
// Reset argument index
i =0;
// Array to store PIDs of child processes
pid_t child_pids[MAX_ARGS];
// Loop through the commands separated by pipes
while (args[i]!= NULL && pipe_count >=0){
char *command = args[i];
char *full_path = resolve_path(command);
if (full_path == NULL){
fprintf(stderr, "Command not found: %s
", command);
return 1;
}
printf("%d",pipe_count);
if (pipe_count >0){
// Create a pipe for every command except the last one
puts("yes");
int pipes[2];
if (pipe(pipes)==-1){
perror("Pipe creation failed");
return 1;
}
args[1]= NULL;
for (char **str= args;*str!=NULL ; str++){
printf("[%s]",*str);
}
pid_t pid = fork();
if (pid ==0){
for (char **str= args;*str!=NULL ; str++){
printf("[%s]",*str);
}
// Child process
if (pipe_count >0 && i !=0){
// Redirect stdin from the read end of the previous pipe
dup2(pipes[0], STDIN_FILENO);
close(pipes[0]);
}
if (pipe_count >0 && i != pipe_count){
// Redirect stdout to the write end of the current pipe
dup2(pipes[1], STDOUT_FILENO);
close(pipes[1]);
}
// Close all pipe file descriptors
for (int j =0; j < pipe_count *2; j++){
close(pipes[j]);
}

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!