Skip to content

Commit

Permalink
Merge pull request BVLC#3378 from BonsaiAI/fix-temp-dir-creation-failure
Browse files Browse the repository at this point in the history
Safely create temporary files and directories
  • Loading branch information
ronghanghu committed Nov 28, 2015
2 parents 4e9b449 + 33905d5 commit 62ed0d2
Showing 1 changed file with 31 additions and 13 deletions.
44 changes: 31 additions & 13 deletions include/caffe/util/io.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,51 @@
#define CAFFE_UTIL_IO_H_

#include <boost/filesystem.hpp>
#include <iomanip>
#include <iostream> // NOLINT(readability/streams)
#include <string>

#include "google/protobuf/message.h"

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/format.hpp"

#ifndef CAFFE_TMP_DIR_RETRIES
#define CAFFE_TMP_DIR_RETRIES 100
#endif

namespace caffe {

using ::google::protobuf::Message;
using ::boost::filesystem::path;

inline void MakeTempFilename(string* temp_filename) {
temp_filename->clear();
const path& model = boost::filesystem::temp_directory_path()
/"caffe_test.%%%%%%";
*temp_filename = boost::filesystem::unique_path(model).string();
}

inline void MakeTempDir(string* temp_dirname) {
temp_dirname->clear();
const path& model = boost::filesystem::temp_directory_path()
/"caffe_test.%%%%%%";
const path& dir = boost::filesystem::unique_path(model).string();
bool directoryCreated = boost::filesystem::create_directory(dir);
CHECK(directoryCreated);
*temp_dirname = dir.string();
const path& model =
boost::filesystem::temp_directory_path()/"caffe_test.%%%%-%%%%";
for ( int i = 0; i < CAFFE_TMP_DIR_RETRIES; i++ ) {
const path& dir = boost::filesystem::unique_path(model).string();
bool done = boost::filesystem::create_directory(dir);
if ( done ) {
*temp_dirname = dir.string();
return;
}
}
LOG(FATAL) << "Failed to create a temporary directory.";
}

inline void MakeTempFilename(string* temp_filename) {
static path temp_files_subpath;
static uint64_t next_temp_file = 0;
temp_filename->clear();
if ( temp_files_subpath.empty() ) {
string path_string="";
MakeTempDir(&path_string);
temp_files_subpath = path_string;
}
*temp_filename =
(temp_files_subpath/caffe::format_int(next_temp_file++, 9)).string();
}

bool ReadProtoFromTextFile(const char* filename, Message* proto);
Expand Down

0 comments on commit 62ed0d2

Please sign in to comment.