title: Is a move operation in Unix atomic?
body: <p>Suppose there are 2 processes P1 and P2, and they access a shared file <code>Foo.txt</code>. </p>
  
  <p>Suppose P2 is reading from <code>Foo.txt</code>. I don't want P1 to write to <code>Foo.txt</code> while P2 is reading it. </p>
  
  <p>So I thought I could make P1 write to <code>Foo.tmp</code> and as a last step, rename <code>Foo.tmp</code> to <code>Foo.txt</code>. My programming language is Java</p>
  
  <p>So my question is, would this ensure that P2 reads the correct data from <code>Foo.txt</code>? Would the rename operation be committed once P2 completes reading the file?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I tried to recreate this scenario as follows:</p>
  
  <p>My P1 code is something like this:</p>
  
  <pre><code>File tempFile = new File(path1);
  File realFile = new File(path2);
  BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
  for(int i=0;i&lt;10000;i++)
      writer.write("Hello World\n");
  writer.flush();
  writer.close();
  tempFile.renameTo(realFile);
  </code></pre>
  
  <p>and my P2 code is :</p>
  
  <pre><code>BufferedReader br = new BufferedReader(new FileReader(file)); 
  String line = null;
  while(true) {
    while((line=br.readLine())!=null){
        System.out.println(line);
        Thread.sleep(1000);
    }
    br.close();
  }
  </code></pre>
  
  <p>My Sample shared File:</p>
  
  <pre><code>Test Input
  Test Input
  Test Input   
  </code></pre>
  
  <p>I'm starting P1 and P2 almost simulataneously (P2 starting first). </p>
  
  <p>So according to my understanding, even though P1 has written a new Foo.txt, since P2 is already reading it, it should read the old Foo.txt content until it re-opens a BufferedReader to Foo.txt. </p>
  
  <p>But what actually happens is P2 reads <code>Test Input</code> thrice, as is expected from the input, but after that it reads the new content which was written by P1. </p>
  
  <p>Output from P2:</p>
  
  <pre><code>Test Input
  Test Input
  Test Input 
  Hello World
  Hello World
  Hello World
   .
   .
   .
  </code></pre>
  
  <p>So it doesn't work as it should. Am I testing this scenario wrong? I feel like there's something I'm missing out.</p>