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!