开发者

execvp arguments

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜