Helllo everybody,
I have this example code:
pid = fork();
if (pid == 0) {
execvp(argv[2],&argv[2]);
perror("Error");
}else {
wait(NULL);
}
From man exec
I understand that
" The first argument, by convention, should point to the filename associated with the file being executed".
So, if I execute my program this way:
./a.out 5 ls
The command ls will be executed.
What about the second argument? the manual says
"The array of pointers must be terminated by a NULL pointer"
and I don't see a NULL pointer here nor I understan what is the function of &argv[2]
here.
Thank you very much!
The second argument to execvp
is the array of char*
s that will become the resulting process's argv
. In order for execvp
to know how long this array is, the last "real" element must be followed by NULL
, e.g., in order to pass {"foo", "bar"}
as the new argv
, the second argument to execvp
must refer to the array {"foo", "bar", NULL}
. In your case, as the argv
array passed to your program's main
is already terminated by a NULL
entry of its own, you can pass &argv[2]
to execvp
directly without having to add on a NULL
yourself.
When you execute a.out, it most likely has a main
like this:
int main(int argc, char *argv[])
/* argv contains this. */
argv[0] == "a.out"
argv[1] == "5"
argv[2] == "ls"
argv[3] == NULL /* Here is your terminator. */
So when you are passing argv[2]
to execvp
everything is in place, but the array starts at 2 (starts with ls
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With