I am trying to implement a simple shell program that runs user input commands. I want the user to enter "ls" or "dir" and have the shell run /bin/ls or /bin/dir . For the execve argument what would be correct:
char *args[] ={"/bin/", "ls", NULL};
//Fork, pid, etc...then
execve(args[0], args+1, NULL);
Or would it be something different?? I've see some people using /bin/ls
as the pathname and then no arguments or ls
as the pathname and \bin
for the environment? I tried what I had above and it didn't work so I want to know if it is the arguments I am sending it or whether I should be looking elsewhere in my code for the problem. Note I am not interested in other variations of execve such as execvp. I am on a Linux system. Thanks
The pathname in execve()
must be the full path to the executable, such as /bin/ls
. If using execvpe()
, you could use ls
alone as the pathname, but as you already specified, you don’t want to use that.
The arguments should be an array of strings, one for each space-separated argument specified on the command line. The last one should be NULL. The first argument should be the pathname itself. For example:
char* args[] = {"/bin/ls", "-la", "foo/bar", NULL};
The environment variables cannot be omitted when using execve()
. In some implementations, NULL
can be passed as the last argument to execve()
, but this is not standard. Instead, you should pass a pointer to a null pointer; essentially an empty array of environment variables.
char *args[] ={"/bin/ls", "-foo", "bar", NULL};
//Fork, pid, etc...then
char* nullstr = NULL;
execve(args[0], args, &nullstr);