I am trying to create a simple shell using C for linux. I cannot figure out why execvp() keeps failing. I know execvp doesn't require a path to be passed with the arguments. I tried following someone's recommendation by running the char array of my commands through strtok.
I keep getting execvp has failed: no such file or directory. I am just passing a simple "ls" as my command to test.
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXARGS 20
#define CMDPROMPT "theshell>"
#define ARGPROMPT "Next argument: "
#define prompt(n) printf("%s", (n) == 0 ? CMDPROMPT : ARGPROMPT);
int main(int argc, char* argv[])
{
char arg[MAXARGS] = {0};
int i = 0,
should_run = 1, pid, exitstatus;
while (should_run)
{
prompt(*arg);
fgets(arg, MAXARGS, stdin);
char *arg = strtok(arg, " ");
char *arg_tok[MAXARGS];
while(arg)
{
arg_tok[i++] = arg;
arg = strtok(NULL, " ");
}
pid = fork();
switch(pid)
{
case -1:
perror("Fork Failed\n");
exit(1);
case 0:
execvp(arg_tok[0], arg_tok);
perror("execvp has failed");
exit(1);
default:
while( wait(&exitstatus) != pid );
printf("Child process exited with status %d, %d\n", exitstatus>>8, exitstatus&0377);
}
}
}
while()loop, you needarg_tok[i] = NULL;or initializechar *arg_tok[MAXARGS] = {NULL};-- the next pointer after your last argument must beNULL. Fromman 3 execvpyou see"The array of pointers must be terminated by a null pointer."char *arg = strtok(arg, " ");SHADOWSchar arg[MAXARGS] = {0};. Always compile with warnings enabled and for gcc/cland add-Wshadowto catch shadowed variables.