C语言 execvp 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6274166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:52:00  来源:igfitidea点击:

execvp arguments

cunixexec

提问by Christian Wagner

Helllo everybody,

大家好,

I have this example code:

我有这个示例代码:

pid = fork();
if (pid == 0) {
   execvp(argv[2],&argv[2]);
   perror("Error");
}else {
wait(NULL);

}  

From man execI understand that

man exec我了解

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

命令 ls 将被执行。

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.

我在这里没有看到 NULL 指针,也不明白&argv[2]这里的功能是什么。

Thank you very much!

非常感谢!

回答by jwodder

The second argument to execvpis the array of char*s that will become the resulting process's argv. In order for execvpto 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 execvpmust refer to the array {"foo", "bar", NULL}. In your case, as the argvarray passed to your program's mainis already terminated by a NULLentry of its own, you can pass &argv[2]to execvpdirectly without having to add on a NULLyourself.

的第二个参数execvpchar*将成为结果进程的 s的数组argv。为了execvp知道这个数组有多长,最后一个“真实”元素必须跟在后面NULL,例如,为了{"foo", "bar"}作为新的传递argv,第二个参数execvp必须引用数组{"foo", "bar", NULL}。在您的情况下,由于argv传递给您的程序的数组main已经被NULL其自己的条目终止,您可以直接传递&argv[2]execvp而无需自己添加NULL

回答by cnicutar

When you execute a.out, it most likely has a mainlike this:

当你执行 a.out 时,它很可能是main这样的:

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 execvpeverything is in place, but the array starts at 2 (starts with ls).

所以当你传递argv[2]execvp一切都到位时,但数组从 2 开始(以 开头ls)。