Why dup2 has to be atomic? What can happen in between close(oldFd) dup(newFd)?
<p>There is a question in my Operating Systems test about which I'm not sure: </p>

<p>given the following code: </p>

<pre><code>int fd = open("File", O_RDWR);
dup2(fd, 1);
write(1, "Hi", 2);
exit(0); 
</code></pre>

<hr>

<p>(1)How can you replace the dup2() call using others system calls? </p>

<p>My answer:</p>

<pre><code> close(1);
 dup(fd);
</code></pre>

<hr>

<p>(2) Substituting the code of the answer (1) in the given code, what could happen during the execution of the generated executable, which underlines the necessity that dup2() is an <strong>atomic</strong> operation? </p>

<p>In this case, with the 'given' code I'm not able to find a counterexample; my counterexample is: </p>

<pre><code>int fd = open("File", O_RDWR);
if(fork() == 0){
  write(1, "a", 1);
}
close(1);
dup(fd);
write(1, "Hi", 2);
exit(0);
</code></pre>

<p>and I say that with this example if the line 'write(1, "a", 1)' is scheduled between the 'close' and the 'dup', there will be an error because no file with fd = 1 would exist; but I'm not able to find a possible 'special case' with the code given at the beginning. I am wondering if there's ambiguity in the exercise, or I didn't understand something.
Thanks in advance!</p>