Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

// C Program How might I modify this code to handle any number of commands piped together? such as ls | wc or ls |

// C Program

How might I modify this code to handle any number of commands piped together? such as ls | wc or ls | wc -l | ps -elf etc..

#include

#include

#include

#include

#include

#include

// keeps track of cmd parameters

typedef struct param {

char *param;

struct param *next;

} pt;

// parses individual commands

typedef struct cmd_list {

char *cmd;

int param_count;

pt *param_list;

char * input_file_name;

char *output_file_name;

struct cmd_list *next;

} cl;

// keeps track of main commands that are piped

typedef struct list {

cl *head;

cl *tail;

int count;

} pt;

void execommands(clt *cmds) {

clt *cmd = cmds;

for (int i = 1; i < cmds->count-1; i++) {

int pipes[2] = {-1, -1};

pid_t pid = -1;

clt *temp = NULL;

pipe(pipes);

pid = fork();

switch (pid) {

case -1:

perror("fork failed");

break;

case 0:

{

char **rhp_argv = NULL;

char *rhp = NULL;

pt *temp = NULL;

int i = 1;

int flag_count = 0;

char flag_string[100] = "";

temp = cmd->param_list;

if (dup2(pipes[STDIN_FILENO], STDIN_FILENO) < 0) {

perror("child process failed dup2");

_exit(EXIT_FAILURE);

}

close(pipes[STDIN_FILENO]);

close(pipes[STDOUT_FILENO]);

rhp = cmd->cmd;

if(0 != cmd->param_count) {

rhp_argv = (char **) calloc((cmd->param_count), sizeof(char *));

rhp_argv[0] = rhp;

while(temp != NULL) {

if (flag_count > 0 && temp->param[0] == '-')

memmove(temp->param, temp->param + 1, strlen(temp->param));

}

strcat(flag_string, temp->param)

flag_count++;

temp = temp->next

}

rhp_argv[i] = strdup(flag_string);

i++;

}

else {

rhp_argv = (char **) calloc(2, sizeof(char *));

rhp_argv[0] = rhp;

}

execvp(rhp_argv[0], rhp_argv);

perror("child cannot exec program");

_exit(EXIT_FAILURE);

if(cmd->param_count != 0) {

for(int celm = 0; celm < flag_count; i++) {

free(rhp_argv[i]);

rhp_argv[i] = NULL;

}

}

free(rhp_argv);

rhp_argv = NULL;

free(temp);

}

break;

default:

int status;

waitpid(pid, &status, 0);

break;

} // end switch

} // end for

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

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

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

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

Get Started

Students also viewed these Databases questions