0

There is a question in my Operating Systems test about which I'm not sure:

given the following code:

int fd = open("File", O_RDWR);
dup2(fd, 1);
write(1, "Hi", 2);
exit(0); 

(1)How can you replace the dup2() call using others system calls?

My answer:

 close(1);
 dup(fd);

(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 atomic operation?

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

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

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!

  • "What can happen in between close(oldFd) dup(newFd)?" - Everything. – too honest for this site Sep 10 '16 at 15:46
  • `fork()` doesn't help, because the two processes each have their own copy of the file descriptor. On the other hand, a signal-handler or a second thread *could* easily do an `open()` or `close()` between the `close()` and the `dup()`, so the new file-descriptor used by `dup()` would *not* be the one `close()` made available. – EOF Sep 10 '16 at 16:27
  • @EOF So I can simply add a new signal handler that performs an open() and it's ok!?! thank you so much!! :) – Giovanni Ciampi Sep 10 '16 at 18:22
  • @GiovanniCiampi: Well, if the normal (sequential) code flow literally contains `close(stdout); dup(fd);`, the race-window could be *quite* small. Which means that you'd have to be *very* precise with your signal (or second thread) to reliably hit it. On the other hand, hard to reproduce bugs are probably the worst kind. – EOF Sep 10 '16 at 18:26
  • @EOF Perfect, very good help btw!! Thank you so much!! – Giovanni Ciampi Sep 10 '16 at 18:31

0 Answers0