title: Multiple processes write to the same file (C)
body: <p>There is a program (Ubuntu 12.04 LTS, a single-core processor):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;sys/types.h&gt;
  
  int main(){
  
      mode_t mode = S_IRUSR | S_IWUSR;
      int i = 0, fd, pid;
      unsigned char pi1 = 0x33, pi2 = 0x34;
      if((fd = open("res", O_WRONLY | O_CREAT | O_TRUNC, mode)) &lt; 0){
  
          perror("open error");
          exit(1);
      }
  
  
  
      if((pid = fork()) &lt; 0){
  
         perror("fork error");
         exit(1);
      }
  
      if(pid == 0) {
  
  
         if(write(fd, &amp;pi2, 1) != 1){
  
             perror("write error");
             exit(1);
         }  
      }else{
  
         if(write(fd, &amp;pi1, 1) != 1){
  
             perror("write error");
             exit(1);
         }  
      }
  
      close(fd);
      return 0;
  }
  </code></pre>
  
  <p>The idea is to open the file for writing, then going fork. The position at which there will be a record total for both processes. The strange thing is that if you run the program, it's output to a file "res" is not constant: I have infuriated then 34 then 4 then 3. The question is why such a conclusion? (After all, if the position is shared, then the conclusion must be either 34 or 43.).</p>
  
  <p>In my suspicion, the process is interrupted in the function write, when he found a position in which to write.</p>