命令行参数如何工作? [英] How do command line arguments work?
问题描述
正如问题所提到的,命令行参数如何在C(通常是任何语言)中工作。我能想到的逻辑解释是,操作系统在启动过程时会为其设置某种环境值。
但是,如果确实如此,我将不能以argp [i]等身份访问它们(我修改了main函数,期望将第二个参数作为char ** argp而不是argv)。请解释。
As the question mentions, how do command line arguments work in C(in general any language). The logical explanation I could think of is, the operating system sets some kind of environmental values for the process when it starts. But if it's true I should not be able to access them as argp[i] etc(I modified the main to expect the 2nd argument as char **argp instead of **argv). Please explain.
推荐答案
与其他答案相比,我将尽力解释实现。
我肯定有一些错误,但是希望它能正确地描述相关部分。
I'll try to explain the implementation a bit more than other answers.
I'm sure there are inaccuracies, but hope it describes the relevant parts well enough.
在外壳下,键入。/ myprog abc
。
shell对其进行了解析,并指出您要使用三个参数运行 ./ myproj
。
它调用 fork
来创建一个新进程,其中将运行 ./ myprog
。
仍在运行shell程序的子进程将准备一个由5个字符指针组成的数组。第一个将指向字符串 ./ prog
,后三个将指向字符串 a
, b
和 c
,最后一个设置为NULL。
接下来,它调用 execve
函数,以创建的参数数组运行 ./ myprog
。
execve
将 ./ myprog
加载到内存中,而不是shell程序中。它释放外壳程序分配的所有内存,但确保保留参数数组。
在新程序中,调用 main
,并使用参数数组作为 argv
传递给它。
Under the shell, you type ./myprog a b c
.
The shell parses it, and figures out that you want to run ./myproj
with three parameters.
It calls fork
, to create a new process, where ./myprog
would run.
The child process, which still runs the shell program, prepares an array of 5 character pointers. The first will point to the string ./prog
, the next three are to the strings a
, b
and c
, and the last is set to NULL.
Next, it calls the execve
function, to run ./myprog
with the parameter array created.
execve
loads ./myprog
into memory, instead of the shell program. It releases all memory allocated by the shell program, but makes sure to keep the parameter array.
In the new program, main
is called, with the parameter array passed to it as argv
.
这篇关于命令行参数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!