UNIX & GNU/Linux - System calls - Using execve()

The execve() system call function is used to execute a binary executable or a script.
The function returns nothing on success and -1 on error.

The first parameter must be the path of a binary executable or a script.
The second must be an array of pointers on a character (char *myArray[]), and the last pointer must be set to NULL.
The third parameter must be an environment.

Using the execve() syscall

First example

 * Badprog.com
 * main.c

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

int     main()
  int e;
  char *envp[] = { NULL };
  char *argv[] = { "/bin/ls", "-l", NULL };

  e = execve("/bin/ls", argv, envp);
  if (e == -1)
      fprintf(stderr, "Error: %s\n", strerror(errno));
  return 0;


gcc main.c -o execve-me ; ./execve-me


The output is a classic ls -la:

drwxr-xr-x  2 badprog tutorial  4096 March  6 19:03 .
drwxr-xr-x 39 badprog tutorial  4096 March  6 18:51 ..
-rwxr-xr-x  1 badprog tutorial  7031 March  6 19:03 execve-me
-rw-r--r--  1 badprog tutorial   385 March  6 19:03 main.c

Second example

Using execve() system call function is also as follows.

#include <unistd.h>
#include <stdlib.h>

int main(int c, char *v[], char **env)
    char *exePath = "/bin/ls";
    char *myArray[] = {NULL, NULL, NULL, NULL};

    myArray[0] = "hello";
    myArray[1] = v[2];
    myArray[2] = v[3];
    execve(exePath, myArray, env);

    return (0);

We can compile this simple example:

$ gcc main.c

And execute it:

$ ./a.out what!

The result is a list of your files present in the current directory even with the first argument set as "what!". Because we set the binary executable to execute the famous "ls" in our program (/bin/ls).

OK, let's try to add some options now:

$ ./a.out what! -l

It lists all files present on the current directory but in line thank to the -l option.
Let's try another example:

$ ./a.out what! -l -a

It lists all files present on the current directory, in line, with the "." and ".." ones. Thanks to the -l and -a options!

Indeed, we replaced the second and third element of myArray (myArray[1] and myArray[2]) by the second and the third argument passed as our a.out executable (-l and -a).

We also note that the first element does not have any effect when we assign it a value with no consequence.
In our example, "hello" does nothing.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.