C++-如何在程序终止后完成一些任务

C++ - How to do some tasks after program is terminated

本文关键字:任务 终止 程序 C++-      更新时间:2023-10-16

我在C++中编写了blow代码:

#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
    ofstream sf;
    sf.open("script_temp_file_id_b01.py", ios::out);
    system("attrib script_temp_file_id_b01.py +h +s +a");
    sf << "name = input("Enter your name: ")n";
    sf << "print("Hello", name)";
    sf.close();
    system("script_temp_file_id_b01.py");
    system("attrib script_temp_file_id_b01.py -h -s -a");
    system("del script_temp_file_id_b01.py");
    return 0;
}

该程序打开一个文件并在其中写入blow python代码:

name = input("Enter your name: ")
print("Hello", name)

然后运行它。

当程序运行此代码时:

system("script_temp_file_id_b01.py");

脚本将被执行。

但是,如果用户在脚本执行期间关闭程序,则以下两行将不会执行,脚本文件也不会删除:

system("attrib script_temp_file_id_b01.py -h -s -a");
system("del script_temp_file_id_b01.py");

我该怎么做?

这取决于程序的运行方式。如果您使用CTRL-C中断程序执行,则可以捕获此事件。在这种情况下,这个答案会对你有所帮助。

通常情况下,在执行之后不可能从程序中运行代码。但你可以捕捉到大多数可能导致你的程序在早期阶段被杀的事件。