Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execvp arguments

Tags:

c

unix

exec

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!

like image 507
Christian Wagner Avatar asked Jan 20 '23 13:01

Christian Wagner


2 Answers

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.

like image 175
jwodder Avatar answered Jan 22 '23 04:01

jwodder


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).

like image 42
cnicutar Avatar answered Jan 22 '23 02:01

cnicutar