Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Open target file with O_EXCL for smpi_copy_file.
[simgrid.git] / src / smpi / internals / smpi_global.cpp
index 741fc10..33efd33 100644 (file)
 #include <array>
 #include <boost/algorithm/string.hpp> /* split */
 #include <boost/tokenizer.hpp>
+#include <cerrno>
 #include <cinttypes>
 #include <cstdint> /* intmax_t */
+#include <cstring> /* strerror */
 #include <dlfcn.h>
 #include <fcntl.h>
 #include <fstream>
@@ -360,8 +362,10 @@ static void smpi_copy_file(const std::string& src, const std::string& target, of
 {
   int fdin = open(src.c_str(), O_RDONLY);
   xbt_assert(fdin >= 0, "Cannot read from %s. Please make sure that the file exists and is executable.", src.c_str());
-  int fdout = open(target.c_str(), O_CREAT | O_RDWR, S_IRWXU);
-  xbt_assert(fdout >= 0, "Cannot write into %s", target.c_str());
+  XBT_ATTRIB_UNUSED int unlink_status = unlink(target.c_str());
+  xbt_assert(unlink_status == 0 || errno == ENOENT, "Failed to unlink file %s: %s", target.c_str(), strerror(errno));
+  int fdout = open(target.c_str(), O_CREAT | O_RDWR | O_EXCL, S_IRWXU);
+  xbt_assert(fdout >= 0, "Cannot write into %s: %s", target.c_str(), strerror(errno));
 
   XBT_DEBUG("Copy %" PRIdMAX " bytes into %s", static_cast<intmax_t>(fdin_size), target.c_str());
 #if SG_HAVE_SENDFILE