The exec Family of functions
- In this article, we’ll talk about exex() family of functions, what they do , and the differences between them.
- These functions are used to execute a file, and they replace the current processes image with a new process image once they are called. Even though they are very similar, there are differences between them, and each one of them receives different information as arguments.
- execl()
execl() receives the location of the executable file as its first arguments, The next arguments will be available to the file when its executed, The last argument has to be NULL
Syntax:
int execl(const char *pathname, const char *arg,…,NULL);
Let’s look at the example ,we need to make sure to include unistd.h
#include
#include
int main()
{
printf(“This is the program for creating a process using execl() system call\n”);
execl(“/bin/ps”, “ps”, “-l”, NULL);
printf(“This line never executes\n”);
return 0;
}
The command we are running is ps which is located at /bin/ps. The first argument available to a program need to be the program itself. and the second argument is –l it will give full information about the process and last arguments in the program is NULL it means end of the list
2.execlp()
execlp() is very similar to ececl() however, execlp() uses the PATH environment variable to look for the file. Therefore, the path to the executable file is not needed.
Syntax:
execlp(const char *file, const char *arg ,…,NULL);
Let’s see an example:
#include
#include
int main()
{
printf(“This is the program for creating a process using the execlp() system call\n”);
execlp(“ps”, “-l”, NULL);
printf(“This line never executes\n”);
return 0;
}
Since ps is already located in the PATH environment variable,we didn’t have to specify its location.
3.execv()
execv(), unlike execl(),receives a vector of arguments that will be available to the executable file. in addition, the last element of the vector has to be NULL.
Syntax:
int execv(const char *pathname, char *const argv[]);
Let’s see an example:
#include
#include
int main()
{
char *path = “/bin/ps”; // Correct full path
char *args[] = {“ps”, “-l”, NULL}; // Correct args
printf(“This is the program for creating a process using execv() system call()\n”);
if (execv(path, args) == -1)
{
perror(“execv failed”);
}
printf(“This line will only execute if execv() fails\n”);
return 0;
}
4.execvp()
Just like execlp() ,execvp() looks for the program in the PATH environment variable
Syntax:
int execvp(const char *file, char *const argv[]);
#include
#include
int main()
{
char *path = “ps”;
char *args[] = {“ps”, “-l”, NULL};
printf(“This is the programming for creating the process using the execvp() system call\n”);
execvp(path, args);
printf(“This line will never execute\n”);
return 0;
}