This section is basically about the exec
family and the different types of minor extensions.
But before that, we need to understand main
function parameters such as argc
and argv
.
main
- argc
and argv
int main(int argc, char* argv[]) {
/*
Misc code here
*/
}
argc
: This is known as the argument counter which keeps track of the number arguments in the argv
array.argv
: This is the argument array (array of strings) which stores the various arguments that are passed to the executable file.
./executable arg1 arg2
.argv[0]
always contains the path to the executable.exec
familyThese are a family of functions/syscalls that allow for the execution of executables through command line interfaces such as the shell.
execlp
and execvp
.
p
instead of exec
is because it does a path search for us in the $PATH
all the way until it finds the executable we called.exec
needs to be used, make sure to use it in the WSL/Linux format.NULL
terminated to work properly.execlp
int execlp(const char *file, const char *arg, .../* (char *) NULL */)
execvp
int execvp(const char *file, char *const argv[])
int main() {
// Array of strings
char* args[] = {
"args", // *** argv[0]: program name ***
"arg1",
"arg2",
"arg3",
NULL
};
// execvp -> Use either one NOT both
execvp(
"./args",
args
);
// execlp -> Use either one NOT both
execlp(
"./args",
"args", // *** argv[0]: program name ***
"arg1",
"arg2",
"arg3",
NULL
)
printf("Failed.\\n"); // This line is reached if the execution fails
return 0;
}
<aside> 📌
This is very important to know that this line printf("Failed.\\n")
will never be reached if the exec
function is successful. The exec
function essentially acts as a “wrapper” which “wraps” the main
function or whatever function calls it. (In actual terms, it replaces the current process image with the new program. This means the rest of the code after the exec
call will never execute.)
It is important to note this as if this function is called directly in the shell, the shell will never be reached again. Hence, this will have to used in conjunction with the fork
function which will create a child process to handle the exec
function act as a “sacrifice”.
</aside>