Question
// C Program This code is supposed to handle commands like ls, df, who, wc, and their flags. This code works if there is zero
// C Program
This code is supposed to handle commands like ls, df, who, wc, and their flags. This code works if there is zero or only one flag but breaks if there is two or more such as ls -l -a for example. when more than one flag is entered, perror is triggered saying there is a bad address. I am unsure how to change it so that it accepts more than one flag.
#include
#include
#include
#include
#include
#include
typedef struct param {
char *param;
struct param *next;
} pt;
typedef struct cmd_list {
char *cmd;
int param_count;
pt *param_list;
struct cmd_list *next;
} clt;
void execommands(clt *cmds) {
clt *cmd = cmds;
pid_t pid = fork();
switch(pid) {
case -1:
// error return break;
case 0: {
char ** rhp_argv = NULL;
char * rhp = NULL;
pt *temp = NULL;
int i = 1;
temp = cmd->param_list;
rhp = cmd->cmd;
// allocate memory for rhp_argv
if(0 != cmd->param_count)
rhp_argv = (char **) calloc((cmd->param_count+1), sizeof(char *));
// set first element to command rhp_argv[0] = rhp;
// add remaining parameters to rhp_argv
temp = cmd->param_list;
while(temp != NULL) {
rhp_argv[i] = strdup(temp->param);
i++;
temp = temp->next;
}
}
else {
rhp_argv = (char **) calloc(2, sizeof(char *));
rhp_argv[0] = rhp;
}
execvp(rhp_argv[0], rhp_argv);
// error exit
} default:
{
int status;
waitpid(pid, &status, 0);
break;
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started