在C中退出处理程序

2 c error-handling exception-handling

所有,

我想在我的程序中开发一个退出处理程序.

我是C的新手; 这是关于在C中管理信号的全部内容吗?

我怎么知道我的节目是否以良好的方式结束?

如果没有,退出时如何获得最大信息?

Foo*_*ooF 7

  1. C(C89和C99标准)提供atexit()在程序退出时调用的寄存器功能.这与信号无关.与信号处理程序不同,您可以注册多个退出处理程序.退出处理程序的调用顺序与它们的注册顺序相反atexit().

  2. 惯例是,当程序干净地退出时,它返回退出状态0.这可通过完成return 0main()exit(0)从任何地方在你的程序.

  3. 在Unix/Linux/POSIX类型的操作系统(不确定Windows)中,父进程使用wait()系统调用或其变体获取有关子进程的退出状态信息.

示例:这是一个简单的程序及其输出来演示atexit():

#include <stdlib.h>
#include <stdio.h>

static void exit_handler1(void)
{
    printf("Inside exit_handler1()!n");
}

static void exit_handler2(void)
{
    printf("Inside exit_handler2()!n");
}

int main(int argc, char *argv[])
{
    atexit(exit_handler1);
    atexit(exit_handler2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序生成的输出:

Inside exit_handler2()!
Inside exit_handler1()!
Run Code Online (Sandbox Code Playgroud)