Question: // C Program This code is supposed to handle commands like ls, df, who, wc, and their flags. This code works if there is non
// C Program
This code is supposed to handle commands like ls, df, who, wc, and their flags. This code works if there is non or only one flag but breaks if there is two or more such as ls -l -r for example. 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_list) {
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);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
