Search code examples
cdebuggingexecsystem-calls

Using execve (linux)


Im confused of the use of the systemcall execve. The second parameter should be a pointer to the arguments but it doesnt work, it does however execute correctly when I send the whole command(/bin/bash) + arg as a second parameter.

./test /bin/bash "echo 'this is a test' | wc -c"

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    execve(argv[1], &argv[1], NULL); ////works, but I dont understand how since the 2nd param is wrong.
    return 0;
}

int main(int argc, char *argv[]) {
    execve(argv[1], &argv[2], NULL);  ////doenst work, it should since Im sending the correct aguments.
    printf("hi");
    return 0;
}


Solution

  • From the execve(2) man page:

    argv is an array of pointers to strings passed to the new program as its command-line arguments. By convention, the first of these strings (i.e., argv[0]) should contain the filename associated with the file being executed. The argv array must be terminated by a NULL pointer. (Thus, in the new program, argv[argc] will be NULL.)

    In other words, the arguments list that you pass in the second parameter includes the name of the executable itself (even though that is already specified in the first parameter). This is how executables are able to detect how they're being invoked (e.g. through a symlink) and show the correct name in their "help" output.