title: How to preserve ownership and permissions when doing an atomic file replace?
body: <p>So, the normal POSIX way to safely, atomically replace the contents of a file is:</p>
  
  <ul>
  <li><code>fopen(3)</code> a temporary file on the same volume</li>
  <li><code>fwrite(3)</code> the new contents to the temporary file</li>
  <li><code>fflush(3)</code>/<code>fsync(2)</code> to ensure the contents are written to disk</li>
  <li><code>fclose(3)</code> the temporary file</li>
  <li><code>rename(2)</code> the temporary file to replace the target file</li>
  </ul>
  
  <p>However, on my Linux system (Ubuntu 16.04 LTS), one consequence of this process is that the ownership and permissions of the target file change to the ownership and permissions of the temporary file, which default to <code>uid</code>/<code>gid</code> and current <code>umask</code>.</p>
  
  <p>I thought I would add code to <code>stat(2)</code> the target file before overwriting, and <code>fchown(2)</code>/<code>fchmod(2)</code> the temporary file before calling <code>rename</code>, but that can fail due to <code>EPERM</code>.</p>
  
  <p>Is the only solution to ensure that the <code>uid</code>/<code>gid</code> of the file matches the current user and group of the process overwriting the file? Is there a safe way to fall back in this case, or do we necessarily lose the atomic guarantee?</p>