1 c++ file-io global-variables signal-handling
在C++中,我有一些需要写入临时目录的函数.理想情况下,只创建一个他们都写入的临时目录(以最小化I/O开销).程序退出时,应自动删除该目录.
但是,我不想在main函数中处理temp目录的创建和删除,因为我认为只有实际使用该目录的函数才应该负责它的创建和删除.并且主函数不一定知道根本使用临时目录.
这是我尝试过的(参见下面的代码):可以从任何地方全局调用的getTempDir()函数仅在其第一次调用时创建目录,并在每次调用时返回目录名称.在第一次调用时,它还会为一个小的DirRemover对象创建一个静态boost :: shared_ptr,该对象的析构函数将删除该目录.程序退出时会自动调用析构函数.
问题是它不会在程序退出失败时调用FileRemover析构函数,或者杀死等等.是否有更好的解决方案?
这是代码:
std::string getTempDir(){
static bool alreadyThere = false;
static std::string name = "";
if(!alreadyThere){
// create dir with
// popen("mktemp -p /tmp","r"))
// and store its name in 'name'
removeAtEnd(name);
alreadyThere = true;
}
return name;
}
void removeAtEnd(const std::string& name){
static boost::shared_ptr<DirRemover> remover(new DirRemover(name));
}
struct DirRemover {
std::string name;
DirRemover(const std::string& n) : name(n){}
~DirRemover(){
// remove 'name' dir with popen("rm -r ...")
}
};
Run Code Online (Sandbox Code Playgroud)
使用popen()执行诸如"rm -r"或"mktemp -p/tmp"之类的事情是一种灾难.在我看来,这是非常糟糕的风格.
特定于UNIX:如果您希望临时文件消失,即使您的应用程序异常终止,那么最好的方法是在打开临时文件后立即取消链接.您的应用程序仍将具有文件句柄,以便您可以使用该文件.当您的应用程序终止并且文件描述符关闭时,该文件将自动从文件系统中删除.
顺便说一下,我看到你正在使用Boost.你确定Boost.Filesystem没有上述功能吗?