How to use execl (example included)

execl is one of the families of exec calls that act as a front end to the execve. The following screenshot refers to man execl:

The arguments for these seven exec functions are difficult to remember. The letters in the function names help somewhat. The letter p means that the function takes a filename argument and uses the PATH environment variable to find the executable file. The letter l means that the function takes a list of arguments and is mutually exclusive with the letter v, which means that it takes an argv[] vector. Finally, the letter e means that the function takes an envp[] array instead of using the current environment.

In the post “Using execve” we saw how it can be used to launch a new process and also pass arguments to it. execl also launches a new process replacing the current one. The syntax of execl is:

int execl(const char *path, const char *arg, ...);

Arguments:
path: Path to the executable that needs to he executed by execl.
arg…: Series of pointers to the arguments that need be passed to executable.

In execve we had to pass an array of pointers as arguments, but in execl we can directly pass the pointers as arguments. These arguments should be NULL terminated.

Example

1. Let us write a simple program to print the arguments passed to it.

# vi hello.c
#include <stdio.h>
main(int argc,char *argv[],char *envp[]){

printf("Filename: %s\n",argv[0]);
printf("%s %s\n",argv[1],argv[2]);
}

2. By convention the first argument should always be the filename and we will be following the same. Let us compile this and name the executable “hello”

# cc hello.c -o hello

3. Now let us write a program to run the executable “hello” using execl.

# vi execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

main() {
char *temp,*temp1,*temp2;
temp="hello";  //filename
temp1="Funny"; 
temp2="world";

execl("hello",temp,temp1,temp2,NULL);
printf("Error");
}

4. Compile the code and execute it:

# cc execl.c -o execl
./execl 

Output:

Filename: hello
Funny world

Thus the program could successfully run the executable “hello” and also pass the arguments to it. Also, note that execl did not return to the calling function, else it would have printed the “Error” statement after the call to execl.

Related Post