In C++, I have a few functions that need to write to a temp directory. Ideally, only one temp directory gets created that they all write to (to minimize I/O overhead). That directory should be automagically removed when the program exits.
However, I don't want to deal with creation and removal of the temp directory in the main function because I think only the functions that actually use the directory should be responsible for its creation and removal. And the main function doesn't necessarily know that a temp directory is used at all.
Here is what I tried (see code below): A getTempDir() function that can be globally called from anywhere creates a directory on its first call only and returns the dir name on every call. On the first call it also creates a static boost::shared_ptr to a little DirRemover object whose destructor will remove the directory. That destructor gets called automatically when the program exits.
The problem is that it won't call the FileRemover destructor on an unsuccessful exit of the program, or a kill etc. Are there better solutions?
Here is the code:
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 ...")
}
};