exit和_exit 两个函数有一定的区别,在某些情况下是不能混用的。首先先看下exit在glibc-2.16.0中是什么定义的?
void
exit (int status)
{
__run_exit_handlers (status, &__exit_funcs, true);
}
它是通过调用一个叫做__run_exit_handlers的函数实现的。那么__run_exit_handlers又是怎么实现的呢?
DEFINE_HOOK (__libc_atexit, (void))
/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered
perform stdio cleanup, and terminate program execution with STATUS. */
void
attribute_hidden
__run_exit_handlers (int status, struct exit_function_list **listp,
bool run_list_atexit)
{
/* We do it this way to handle recursive calls to exit () made by
the functions registered with `atexit' and `on_exit'. We call
everyone on the list and use the status value in the last
exit (). */
while (*listp != NULL)
{
struct exit_function_list *cur = *listp;
while (cur->idx > 0)
{
const struct exit_function *const f =
&cur->fns[--cur->idx];
switch (f->flavor)
{
void (*atfct) (void);
void (*onfct) (int status, void *arg);
void (*cxafct) (void *arg, int status);
case ef_free:
case ef_us:
break;
case ef_on:
onfct = f->func.on.fn;
#ifdef PTR_DEMANGLE
PTR_DEMANGLE (onfct);
#endif
onfct (status, f->func.on.arg);
break;
case ef_at:
atfct = f->func.at;
#ifdef PTR_DEMANGLE
PTR_DEMANGLE (atfct);
#endif
atfct ();
break;
case ef_cxa:
cxafct = f->func.cxa.fn;
#ifdef PTR_DEMANGLE
PTR_DEMANGLE (cxafct);
#endif
cxafct (f->func.cxa.arg, status);
break;
}
}
*listp = cur->next;
if (*listp != NULL)
/* Don't free the last element in the chain, this is the statically
allocate element. */
free (cur);
}
if (run_list_atexit)
RUN_HOOK (__libc_atexit, ());
_exit (status);
}
很长的一段的代码,而且里面也引用了其他的一些函数,我们先暂且不管。先看看函数的注释段:
/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered
perform stdio cleanup, and terminate program execution with STATUS. */
也就是,该函数先递归的调用由atexit或者on_exit注册的函数,并且清空输入输出流,最后调用_exit终止一个进程。这样就比较明了了,exit是对_exit进行的封装,在_exit之前还存在其他的操作。至于_exit函数的源码,我在搜索_exit中出现了好多个版本的_exit,但具体是怎么调用的就不太清楚了。反正我们一定要知道exit是对_exit进行了封装,他们不是等同的就可以了。
至于他们的不同会造成什么影响呢?或者他们之间有什么在使用时要注意的地方吗?这里就引用下别人做的总结,如下:
‘exit()’与‘_exit()’的基本区别在于前一个调用与实施库里用户状态结构 (user-mode constructs)有关的清除工作(clean-up),而且调用用户自定义的清除程序 (译者注:自定义清除程序由atexit函数定义,可定义多次,并以倒序执行),相对 应,后一个函数只为进程实施内核清除工作。
在由‘fork()’创建的子进程分支里,正常情况下使用‘exit()’是不正确的,这是 因为使用它会导致标准输入输出(译者注:stdio: Standard Input Output)的缓冲区被 清空两次,而且临时文件被出乎意料的删除(译者注:临时文件由tmpfile函数创建 在系统临时目录下,文件名由系统随机生成)。在C++程序中情况会更糟,因为静 态目标(static objects)的析构函数(destructors)可以被错误地执行。(还有一些特殊情况,比如守护程序,它们的父进程需要调用‘_exit()’而不是子进程;适用于绝大多数情况的基本规则是,‘exit()’在每一次进入‘main’函数后只调用一次。)
在由‘vfork()’创建的子进程分支里,‘exit()’的使用将更加危险,因为它将影响 父进程的状态。
至于return和exit之间的区别:return是语言层面的,是编程语言中的一个关键字,它表示了调用堆栈的返回。而exit是系统级别,它表示一个进程的结束。那么为什么main函数可以只使用return就可以结束呢?那是因为main隐式的调用了exit函数。