[英]Does calling main from main spawn a new process?
从main调用main是为被调用的main生成一个新进程还是在同一进程中调用main?
我已经读过main返回的值由执行它的进程返回。
它不会创建新流程。 它只是在同一个进程中调用一个函数。
#include<stdio.h>
#include<stdlib.h>
int start=1;
int main()
{
if (start) {
printf("in first call to main, pid=%d\n",getpid());
start=0;
return main();
} else {
printf("in second call to main, pid=%d\n",getpid());
return 1;
}
}
输出:
in first call to main, pid=15482
in second call to main, pid=15482
进程退出状态为1。
它不会创建另一个进程,但它将做的是将main()嵌入其自身。 会发生一些奇怪的事情。 如果您没有明确告诉main您已完全完成它将继续运行并且该过程不会终止; 因为对main的原始调用尚未完成。 当你调用它时它会嵌套在自身内。
好问题。 当我第一次学习CI时有这个弹出窗口。 我最后使用main来重新运行所有内容而不是仅使用循环。 我的老师说这不是一个好习惯。
我已经读过main返回的值由执行它的进程返回。
这是因为C运行时将调用main()
并在执行后执行一些特定于操作系统的操作,以将退出状态设置为返回的main()
。 然而, main()
没有什么特别之处,它只是一个普通的函数。
这特别意味着它不是程序的入口点......真正的入口点是由链接到程序的C运行库提供的,而main()
是从那里调用的。
作为一个例子,看看我最近为DOS .COM
可执行文件的自己的运行时编写的一些代码:
__asm__ (
" .section .comstartup \n"
" .globl __com__start \n"
/* THIS is the real entry point, call a function to get some info
* about the console and then jump to a function getting command
* line arguments from DOS and calling main */
"__com__start: \n"
" call _getcinfo \n"
" jmp argstart \n"
" .text \n");
void __attribute__((__noreturn__)) exit(int status)
{
/* this just calls the DOS function for exiting with exit status */
__asm__ volatile (
"mov $0x4c, %%ah \n\t"
"int $0x21 \n\t"
:
: "a" (status)
);
__builtin_unreachable();
}
static void argstart(void)
{
char *cmdline = (char *)0x81;
argc = 1;
argv[0] = progname();
{
/* some code to populate argv[] */
[....]
}
/* and this could be a quite typical line in any C runtime, just
* call exit() with whatever main() returns: */
exit(main(argc, argv));
}
main函数在同一进程中调用,可以通过打印getpid()返回的值来检查,如下所示:
int main(){
static int i = 2;
if (i>0){
int pid1 = getpid();
printf("Main: %d\n", pid1);
i--;
main();
}
}
输出是
Main: 32323
Main: 32323
这证实了main在与系统调用第一个进程相同的进程中被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.