编写一个测试程序,使用atexit()函数注册一个进程在正常终止时需要调用的函数
时间: 2023-11-27 10:50:13 浏览: 48
以下是一个使用atexit()函数注册进程在正常终止时需要调用的函数的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
void cleanup(void) {
printf("Program is terminating. Cleanup function is called.\n");
}
int main() {
printf("Program is running...\n");
if (atexit(cleanup) != 0) {
fprintf(stderr, "Error: Failed to register cleanup function.\n");
exit(EXIT_FAILURE);
}
printf("Program is ending normally.\n");
exit(EXIT_SUCCESS);
}
```
在这个程序中,我们定义了一个名为`cleanup`的函数,用于在程序正常终止时进行清理操作。然后,在`main`函数中,我们通过调用`atexit`函数来注册这个清理函数。如果`atexit`函数返回非零值,说明注册失败,我们就打印一个错误信息并退出程序。最后,我们调用`exit`函数来结束程序,并指定返回值。当程序正常终止时,`atexit`函数会自动调用注册的清理函数。运行这个程序后,输出结果如下:
```
Program is running...
Program is ending normally.
Program is terminating. Cleanup function is called.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)