4

This is coming off this question. Why is touch calling the dup2() syscall?

$ > strace touch 1 2>&1 | tail
close(3)                                = 0
open("1", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 3
dup2(3, 0)                              = 0
close(3)                                = 0
utimensat(0, NULL, NULL, 0)             = 0
close(0)                                = 0
close(1)                                = 0
close(2)                                = 0
exit_group(0)                           = ?
+++ exited with 0 +++
Community
  • 1
  • 1

1 Answers1

1

It's a historical artifact.

The open()+dup2() pattern comes from the fd_reopen() function, which is used by several of the programs in the coreutils code base.

Prior to coreutils commit e373bb1, fd_reopen() did not do open()+dup2(), but closed the desired file descriptor before opening a new one. This was the case when touch started using this function at coreutils commit 478bd89. Per that commit message, the intent was to reduce the number of file descriptors touch would have open.

toojays
  • 767
  • 6
  • 10