title: System command failing on Linux C++
body: <p>In my program I am copying an executable file from one location to another, and then execute the copied file. When the copied file is executed I get a "permission denied" error. But if I restart my program then the file gets executed without a problem. Can someone please help me with the problem? The code below is simple, but demonstrates the problem.</p>
  
  <pre><code>void copyFile(string _from, string _to)
  {
      std::ifstream  src(_from.c_str());
      std::ofstream  dst(_to.c_str());
  
      dst &lt;&lt; src.rdbuf();
  }
  
  int main()
  {
      string original("./exe_file");
      string dest_file("./exe_dir/exefile");
  
      system("./exe_dir/exefile");  //Fails on first run because exe_dir does not exist.
  
      //mkdir and copy the file.
      mkdir("./exe_dir",S_IRWXO | S_IRWXU | S_IRWXG);
      copyFile(original, dest_file);
  
      //Open the file and close it again to flush the attribute cache.
      int fd = open(dest_file.c_str(),O_RDONLY);
      close(fd);
  
      //The line below fails with system error code 2 (Permission denied) on exefile.
      return system("./exe_dir/exefile");
  {
  </code></pre>
  
  <p>I used 'chmod 777 exe_file' on the original file before executing the program, and after running this program the destination also has the same access rights. I can execute it manually just fine. And every subsequent run of the program is successful. Why does it fail on the first run?</p>