Where does the returned value for 'main' function go?

只谈情不闲聊 提交于 2019-12-04 01:58:15

问题


In C, a function always returns its value to the calling function and never to itself (if return type is not void). Like,

int main()

But since 'main' function is called by the Operating System, which is not a function. So, whom does the 'main' function returns its value? Where does the value go, when its returned using the expression

return(0);

at the end of the program?


回答1:


This is completely OS-specific, but usually the OS invokes a program by

  1. Setting up the program's address space,
  2. Creating a record of the new process somewhere in the OS internals,
  3. Launching its own custom function, which calls main and stores the return value in the OS internals.

The function I'm referring to in (3) is often a good old fashioned C function that just jumps into main so it can capture the return value from main as if it were an ordinary C function (which it in fact is). Afterwards, it stores that value somewhere in OS-land so that processes that need to read the return value can do so.

Hope this helps!




回答2:


As already said, this is OS specific. In UNIX systems it looks something like this:

When you compile a program with gcc, it wraps a startup routine around your main() function. This routine calls your main() function and saves its return value. It then calls the exit() function (which your program might call as well), that does some general clean up. This function then again calls _exit(), which is a system call that tells the OS to save the returned value of your main() function in the process table (where meta information about your process is saved). As soon as another process calls wait() on your process id (PID), your returned value is given to the calling process and your process is removed from the table.

Look at this resource for more information: http://www.johnloomis.org/ece537/notes/Processes/process_environment.html




回答3:


Where does the returned value for 'main' function go?

It is returned to the calling process.

On a POSIX compliant systems if the calling parent process were a C program it could at least retrieve the lowest 8bit of its child's return value by calling wait() or waitpid() after the child ended.




回答4:


most operating systems call main like this:

exit(main(argc, argv, envp));



来源:https://stackoverflow.com/questions/25434850/where-does-the-returned-value-for-main-function-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!