开发者

Context of Main function in C or C++

Does the main function we define in C or C++ run in a process or thread. If it runs in a thread, which process is re开发者_如何学Gosponsible for spawning it


main() is the entry point for your program. C++ (current C++ anyway) doesn't know what a process or thread is. The word 'process' is not even in the index of the standard. What happens before and after main() is mostly implementation defined. So, the answer to your question is also implementation defined.

In general though most operating systems have the concept of process and thread and they have similar meanings (though in Linux, for example, a thread is actually a "light weight process"). You can generally assume that your program will be started in a new process and that main() will then be called by the original thread after the implementation defined initialization.

Since there's plenty of room for the implementation and/or you to start up a whole bunch of threads before main is called though you will probably generally want to consider main() to have been called during the execution of a thread. The best way to think about it though is probably in terms of the standard unless you really have to think about the implementation. The standard doesn't currently know what a process or thread is. C++0x will change that in some way but I'm not sure at this point what the new concepts will be or how they will relate to OS specific constructs.

My answer is specifically addressed at the C++ language part of the question. C is a different language and I haven't used it in a good 10 years so I forget how the globals initialization is specified.


It's a process that you spawn when you execute your program. The main function is called at the beginning of the program. It is all a part of the same program (i.e. one process).


When you ask your OS to start a new process, it initializes data structures for a process and for a single thread inside that process. The initial instruction pointer in that thread context is the process entry point, which is a function provided by your C runtime library. That library-provided entry point converts the environment table and command-line arguments into the format demanded by the C standard, and then calls your main function.


Your whole program is a single process unless it starts fork()ing things, and by default the process has one thread that does everything; main() starts on that thread

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜