I attempted to use execve to run the command: ls -l /tmp
, I'm familiar with the system call usage but I do not know how it runs commands.
I've tried this and i keep getting errors
char *argv[] = {"ls", "-l", NULL};
int exec;
exec = execve("/tmp", argv, NULL);
printf("%d\n", exec);
return (0);
CodePudding user response:
You don't use execve
correctly. The first argument has to be the executable path.
So your code should be
int main(void) {
char *argv[] = {"ls", "-l", "/tmp", NULL};
execve("/bin/ls", argv, NULL);
// Or "/usr/bin/ls", depending where
// is stored 'ls' on your system
// On success theses lines are not reached
perror("execve failed");
return 0;
}
Note that (from man execve):
RETURN VALUE
On success, execve() does not return, on error -1 is returned, and errno is set to indicate the error.
If the execve
call is a success, your program will be replaced by the launched one (ls
here), so the two last lines won't be executed
CodePudding user response:
The first argument to execve
is the path to the program to execute.[1]
char *argv[] = { "ls", "-l", "/tmp", NULL };
execve( "/usr/bin/ls", argv, NULL );
Note that we had to provide the full path to the binary. To avoid this by searching the PATH when needed, we can use one of the "p" variants instead.
char *argv[] = { "ls", "-l", "/tmp", NULL };
execvpe( argv[0], argv, NULL ); # execvpe is a GNU extension.
or
char *argv[] = { "ls", "-l", "/tmp", NULL };
execvp( argv[0], argv );
Finally, the purpose of exec*
is to change the program the current process executes. As such, it only returns on error, and it always returns -1
on error. If you wanted to print the error, you could used perror
.
- To set the path to use as the current work directory, use
chdir
beforeexec*
.
CodePudding user response:
The first argument to execve
must be the path to the program to execute:
exec = execve("/bin/ls", argv, NULL);
The second argument, argv
, must be a list of all the arguments:
char *argv[] = {"ls", "-l", "/tmp", NULL};