Skip to main content Link Menu Expand (external link) Document Search Copy Copied

execve function

C

Function

Reference manual

@see man execve

The execve function is used to execute a program. It replaces the current process image with a new process image loaded from the specified executable file.

If the program executed by execve succeeds execve does not return meaning there’s no need to release any resources. However, if the program fails execve will return and it might be necessary to release the resources associated with the calling process.

Syntax

#include <unistd.h>

int execve(
    const char *pathname,
    char *const argv[],
    char *const envp[]
);

Parameters

  • pathname: The path to the executable file to be executed.

  • argv: An array of strings representing the command-line arguments passed to the new program. By convention the first element of the array should be the name of the executable file and the last element must be NULL.

  • envp: An array of strings representing the environment variables to be passed to the new program. The last element of the array must be NULL.

Return value

  • If the execution is successful, the function does not return. It replaces the current process with the new process.

  • If an error occurs, -1 is returned, and errno is set to indicate the error.

Usage example

In the following example we use the execve function to execute the /bin/ls program and we print an error message if it fails.

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

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

    execve("/bin/ls", argv, envp);
    // If execve returns, an error occurred
    perror("Command execution failed");
    return (EXIT_FAILURE);
}