Answered step by step
Verified Expert Solution
Link Copied!
Question
1 Approved Answer

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

Step: 1

blur-text-image
Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data And Databases

Authors: Jeff Mapua

1st Edition

1978502257, 978-1978502253

Students explore these related Databases questions

Question

How wide are Salary Structure Ranges?

Answered: 3 weeks ago