title: How to avoid race condition when checking if file exists and then creating it?
body: <p>I'm thinking of corner cases in my code and I can't figure out how to avoid problem when you check if file exists, and if it does not, you create a file with that filename. The code approximately looks like this:</p>
  
  <pre><code>// 1
  status = stat(filename);
  if (!status) {
    // 2
    create_file(filename);
  }
  </code></pre>
  
  <p>Between the call to 1 and 2 another process could create the filename. How to avoid this problem and is there a general solution to this type of problems? They happen often in systems programming.</p>