Reputation:
execve()
only works when /bin/
is a prefix to the first argument
e.g. ./test.out ls
finds nothing while ./test.out /bin/ls
works
execve(argv[1], args, getenv("PATH"))
Upvotes: 0
Views: 247
Reputation: 17403
execve
does not search the PATH
directories. The first parameter needs to refer to an actual file reachable from the current directory, so needs to contain /
characters if the file is not in the current directory.
Linux supports execvpe
as a GNU extension which is a cross between the execve
and execvp
POSIX functions. The p
means it will search the PATH
for the file as long as it contains no /
characters. (If it does contain /
characters, it will the same as the non-p
version.) The e
means that a new environment is passed to the function in the third parameter.
OP's code passes an environment to the execve
function that contains only the PATH
environment variable from the original environment. If that is the intention, the same effect can be performed in a POSIX compliant manner by stripping the environment before calling execvp
. This makes use of the extern char **environ;
variable declared by #include <unistd.h>
:
char *env_p = getenv("PATH");
char *args[] = {argv[1], argv[2], NULL};
if (environ[0]) {
environ[0] = env_p;
environ[1] = NULL;
}
if (execvp(argv[1], args) < 0) {
perror("execvp");
exit(EXIT_FAILURE);
}
Upvotes: 0
Reputation: 780909
execve()
doesn't search PATH
for the executable. You have to use execvp()
for that. The p
in the name stands for PATH
.
Upvotes: 3