简体   繁体   English

argc来自哪里?

[英]Where does argc come from?

A new process is created by fork/exec. fork / exec创建一个新进程。 Exec sets up the command line arguments but I don't see that it sets up the number of those arguments to put in argc . Exec设置了命令行参数,但是我看不到它设置了要放入argc的那些参数的数量。

main() is supposed to be the first function to run in the new process but argc is already set by then. main()应该是在新进程中运行的第一个函数,但是那时已经设置了argc

Where is it set? 在哪里设置? It has to be some kind of setup code that counts parameters before main is called but nothing I have read explains what kinds of things this setup code does or where it resides. 它必须是某种设置代码,它可以在调用main之前对参数进行计数,但是我所读过的任何东西都没有解释该设置代码的作用或驻留位置。

Is this in libc ? 这是libc吗? Is this the same on every OS and covered by some specification? 每个操作系统上是否都相同,并包含某些规范? Where would I find what goes on in the setup code besides this? 除此以外,我还能在哪里找到设置代码中的内容? Is it called before instantiating globals? 在实例化全局变量之前调用它吗?

There's plenty of stuff that happens in most implementations before main is called (usually environment set up by something similar to crt0 , the C runtime startup). 在调用main之前,大多数实现中都会发生很多事情(通常是由类似于C运行时启动crt0环境设置的)。

There's also plenty of stuff that may happen after main exits, such as resource closure, atexit exit handlers and so forth. main出口退出 ,还可能发生很多事情,例如资源关闭, atexit退出处理程序等。

The C standards only really cover the stuff that happens in terms of the language, not how implementations do their work under the covers (which is basically what you're asking). C标准仅涵盖语言方面发生的事情,而不涵盖实现如何在后台进行工作(这基本上就是您要的内容)。 Each implementation may do things in different ways but many UNIX types will have something like the afore-mentiond crt0 which does the setup. 每个实现可能以不同的方式执行操作,但是许多UNIX类型将具有前面crt0来执行设置。

The OS takes care of it. 操作系统会处理它。 After all, it is the OS which handles threads and processes. 毕竟,操作系统是处理线程和进程的工具。

Using fork causes to continue at the next line of code. 使用fork将导致继续执行下一行代码。 Exec function family creates a new execution, depending in which you are using the second parameter of the function might be the array of parameters. Exec函数系列将创建一个新的执行,具体取决于您正在使用的函数的第二个参数是参数数组。

#include <unistd.h>


int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
...
ret = execve ("/bin/ls", cmd, env);

In C and C++, main() is called from mainCRTStartup() or a similar function dependent on your build tools. 在C和C ++中, main()是从mainCRTStartup()或依赖于构建工具的类似函数调用的。 If you break in the debugger and examine the callstack you should be able to find the source. 如果您闯入调试器并检查了调用堆栈,则应该能够找到源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM