Reputation: 5784
the following code should call a command with excve
for some reason i doesn't print the contents of the current directory, but still the program returns "ok"
1 #include <stdio.h>
2 #include <unistd.h>
3 int main ()
4 { char *argv[]={"ls",NULL};·
5 char *env[]={"PATH=/usr/local/sbin/:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games",NULL};
6 if(execve("ls",argv,env))
7 { printf("ok\n");
8 }
9 else
10 { printf("not ok\n");
11 }
12 return 0;
13 }
Upvotes: 3
Views: 12185
Reputation: 17312
This doesn't really make much sense
if(execve("ls",argv,env) >0) {
printf("ok\n");
} else {
printf("not ok\n");
}
All exec
functions do not return if they succeed, so if it returns it means it failed, you don't need to check if it returns -1
, second issue is that the first argument to execve()
is the file path not command name, from the man:
execve() executes the program pointed to by filename.
So you just need to:
execve("/bin/ls", argv, env);
/* execve() only returns on error */
perror("execve");
exit(EXIT_FAILURE);
Upvotes: 2
Reputation: 882028
Since execve
does not return on success, it's obvious that the call is failing somehow. It returns -1 on error, which would be treated as true (non-zero). That's why it's saying okay.
The most likely reason is that you haven't specified the full path to the executable, which is a requirement for execve
. Alternatively, if you want the path to be searched, use execvpe
instead. See http://linux.die.net/man/3/exec for the gory details.
Upvotes: 4
Reputation: 2825
Calls to exec don't return when they succeed. You basically replace the calling program with the one you're execing to.
So if you ever run any code past the exec, it means exec failed. I believe exec returns -1, which is why you end up printing ok.
Upvotes: 2
Reputation: 20641
execve returns -1 on error, which evaluates as true when used in a context requiring a boolean. However, there's no point checking the return value, since if execve succeeds then it won't return.
Probably in this case, it's failing because you're not supplying the full path to 'ls'.
Upvotes: 1