最近读 APUE,APUE 7.3 节中说,main 函数 return 相当于
exit(main(argc, argv))
但是在实践程序 8-2 时候出现了问题
下面的程序编译后执行会 core-dump
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int glob = 6;
int
main(void)
{
int var;
pid_t pid;
var = 88;
printf("before vfork\n");
if ((pid = vfork()) < 0) {
printf("vfork error");
exit(-1);
} else if (pid == 0) {
/* 子进程 */
glob++;
var++;
return 0;
//exit(0);
}
printf("pid=%d, glob=%d, var=%d\n", getpid(), glob, var);
return 0;
//exit(0);
}
但是将 return 改为 exit 后却不会
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int glob = 6;
int
main(void)
{
int var;
pid_t pid;
var = 88;
printf("before vfork\n");
if ((pid = vfork()) < 0) {
printf("vfork error");
exit(-1);
} else if (pid == 0) {
/* 子进程 */
glob++;
var++;
//return 0;
exit(0);
}
printf("pid=%d, glob=%d, var=%d\n", getpid(), glob, var);
//return 0;
exit(0);
}
请问是什么样的原因导致第一段程序会出 core-dump 呢?
摘录一段《C语言程序设计-现代方法》9.5章节
return语句和exit函数之间的差异是:不管哪个函数调用exit函数都会导致程序终止,return语句仅当由main函数调用时才会导致程序终止。
PS:你的代码貌似有问题(我在printf上加了计数)
printf("pid=%d, glob=%d, var=%d ->%d<--\n", getpid(), glob, var, ++i);
当使用return 0的时候,运行结果是这样的:
... ...
before vfork
pid=5101, glob=31853, var=-232083051 ->31847<--
before vfork
pid=5101, glob=31854, var=-232083051 ->31848<--
before vfork
pid=5101, glob=31855, var=-232083051 ->31849<--
before vfork
然后停止了
而使用exit 0时,是这样的:
straysh Learning]$./a.out
before vfork
pid=5145, glob=7, var=4195680 ->1<--
http://man7.org/linux/man-pages/man2/vfork.2.html
The vfork() function has the same effect as fork(2),
except that the behavior is undefined if the process created by
vfork() either modifies any data other than a variable of type pid_t
used to store the return value from vfork(), or returns from the
function in which vfork() was called, or calls any other function
before successfully calling _exit(2) or one of the exec(3) family of
functions.
直接return是一个undefined行为. 发生core-dump是正常的.
exit是程序退出,无论在什么函数中调用都会退出,程序退出时,对相应的资源如文件描述符,缓冲区等进行回收。但是return函数退出。假如main函数调用了一个函数func(),在func中使用了return,则程序从func中返回到main中继续执行。但是如果在func中调用exit,则程序会终止退出。所以在main中使用exit和return,由于只有一层函数调用。看上去的效果是一样的。至于fork之后,使用return发生的这种情况就很奇怪了
Look ! when use the 'return' at the end of code !You will probly see it (as the picture show)
If you see those code do not help ...just let me know