[APUE读书笔记] 有关exit 和_exit区别的比较

来源:互联网 发布:杭州亚信软件 编辑:程序博客网 时间:2024/06/05 07:25
最近重新看了一下APUE, chapter 7中讲到进程终止有以下几种方式:
1) 从main返回
2) 调用exit
3) 调用_exit或_Exit
4) 最后一个线程返回
5) 最后一个线程pthread_exit
  其中,对于2,3的区别书上说的是"_exit很快进入内核模式,而exit则执行处理操作",为了更好的理解这句话,我编写了下面的测试例子.(见后面的代码示例)
测试环境:
ubuntu 11.10
gcc 4.7.1
对于main的最后一行分别采用
最近重新看了一下APUE, chapter 7中讲到进程终止有以下几种方式:
1) 从main返回
2) 调用exit
3) 调用_exit或_Exit
4) 最后一个线程返回
5) 最后一个线程pthread_exit
  其中,对于2,3的区别书上说的是"_exit很快进入内核模式,而exit则执行处理操作",于是我编写了下面的测试例子.
  对于main的最后一行分别采用
1) return 0
2) exit (0)
3) _exit (0)
4) _Exit (0)
几种方式,结论如下
** return 0  exit (0)等价,在main返回后,分别会执行下面的动作序列:
    main ends here //先从main返回
    local //释放栈上的局部变量
    my exit 2 called //以出栈的方式调用axexit注册的函数
    my exit 1 called
    global //释放全局数据
** 而_exit (0)  _Exit(0)是等价的,见libC 25.6.5 Termination Internals.
  只产生下面的动作序列:
    main ends here
**** 结论:            
可见 _exit(0)  _Exit(0)的返回速度的确比 exit (0)  return (0)要快,换言之,_exit (0)  _Exit (0) 的确没有做数据的收尾工作就匆匆返回了.
在实际使用中,如果可能不用_exit (0)和_Exit (0)的话,还是少用把    
下面是有关_exit的说明:

DESCRIPTION

The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal.

The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait(2) family of calls.

The function _Exit() is equivalent to _exit(). 

                                                                   
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#include <string>
using std::string;
#include <unistd.h>
void myexit1()
{
    fprintf(stderr,"my exit 1 called\n");
}
void myexit2()
{
    fprintf(stderr,"my exit 2 called\n");
}
class MyClass
{
public:
    MyClass(string name)
    {
        mName = name;
    }
    ~MyClass()
    {
        cout <<mName << endl;
    }
    string mName ;
};
MyClass bb("global");
int main()
{
    MyClass bb("local");
    atexit (myexit1);
    atexit (myexit2);
    fprintf(stderr,"main ends here\n");
    _Exit (0);
}