命令行参数如何从 shell 传递到可执行文件?

How are command line parameters passed from shell to executable?

当我做类似

的事情时
$ ./my-program foo bar

foobar 如何从 shell 传递到 my-program 的内存 space? my-program 是否通过系统调用获取它们?复制它们是内核的工作吗?

(请注意,我知道如何读取和使用命令行参数。这不是我的问题。)

这是 OS 具体的,但在 GNU/Linux:

  1. shell 在其内存中将参数构建为 C 字符串 space。
  2. shell 调用 execve(2) 并将指针传递给这些参数的 NULL 终止数组。
  3. 内核准备执行,包括构建新的内存映射,特别是 allocating the process stack
  4. 内核copies the arguments进入新栈
  5. 内核从其初始 _start 符号开始调度进程
  6. 目标可执行文件现在是 运行
  7. 目标的 glibc 初始化程序(由 gcc 添加)copies the argument pointer from the stack
  8. 最终目标的 main 方法通过指向参数数据的指针被调用。
  9. 目标现在可以通过 argv 指针从它自己的内存 space 访问参数。