zoukankan      html  css  js  c++  java
  • APUE学习笔记——7main()函数启动与退出

    程序的启动与退出过程

    先上图,了解进程运行的机制。



        内核首先调用exec,运行C启动进程,C启动进程会调用main()函数。
        其他所有函数都是由main函数直接或间接调用的。
        从Figure7.2可以看出,内核与用户进程的交互,直接使用的只有三个函数:exec、_exit、_Exit
        exec是用来启动C启动历程的,关于用户进程的退出,主要涉及以下三个函数:
    1. #include <stdlib.h>
    2. void exit(int status); //进行了进程的清理工作,最后应该也是调用了_Exit()或者_exit()
    3. void _Exit(int status);
    4. #include <unistd.h>
    5. void _exit(int status);
    int status表示程序退出的状态。

    程序的终止atexit

    以个程序可以等级至多32个终止程序,这些函数又atexit()登记,由exit()自动调用:
    1. #include <stdlib.h>
    2. int atexit(void (*func)(void));
    3. Returns: 0 if OK, nonzero on error
    exit调用终止程序的顺序与他们登记的顺序相反
    接下来看一个例子
    1. #include "apue.h"
    2. #include "myerr.h"
    3. static void my_exit1(void);
    4. static void my_exit2(void);
    5. int
    6. main(void)
    7. {
    8. if (atexit(my_exit2) != 0)
    9. err_sys("can’t register my_exit2");
    10. if (atexit(my_exit1) != 0)
    11. err_sys("can’t register my_exit1");
    12. if (atexit(my_exit1) != 0) //登记了两次my_exit1
    13. err_sys("can’t register my_exit1");
    14. printf("main is done ");
    15. return(0);
    16. }
    17. static void
    18. my_exit1(void)
    19. {
    20. printf("first exit handler ");
    21. }
    22. static void
    23. my_exit2(void)
    24. {
    25. printf("second exit handler ");
    26. }
    运行:因为return与exit相当,所以在main退出时会执行exit,并调用了登记的两个函数。注意顺序
    1. windeal@ubuntu:~/Windeal/apue$ ./exe
    2. main is done
    3. first exit handler
    4. first exit handler
    5. second exit handler
    注意:两个登记的函数,在return(相当于exit)时被执行,因为exit会做清理工作,会调用登记的两个函数
    如果我们直接使用_exit()或者_Exit()直接退出,则链各个登记的函数变不会被调用。






  • 相关阅读:
    boost编译中的细节问题
    geos编译问题
    安装pytorch的细节记录
    Qt学习-模仿Qt实现一个colorbutton
    BOOST内存管理-intrusive_ptr
    GEOS使用记录
    matlab添加永久路径
    关于浮点数的取值范围以及精度的问题
    vs2010中使用命令行参数
    sprintf fprintf EOF scanf 的返回值 深拷贝与浅拷贝
  • 原文地址:https://www.cnblogs.com/Windeal/p/4284653.html
Copyright © 2011-2022 走看看