According to the man page of dup2, this syscall make a new copy of the old file descriptor. The two descriptors do not share (the close-on-exec flag).

However in case the file descriptor we are trying to duplicate has an fcntl lock associated with it, does the new file descriptor get a new lock ?


Posix locks (F_SETLK etc) are associated with a process, so after a dup2() you still only have one lock on a file. You can list your locks with lslocks. If you close one of the 2 fds you will drop the lock. If you change the lock with one of the fds, the other will change too. After a fork() the child has no locks. See the fcntl man page for details. This Posix spec says dup2() will share any locks.

You can do simple tests in Python using lockf() for ease of use, as it is implemented via fcntl(), eg:

import os, fcntl
pid = os.getpid()
fd = open("/tmp/try","rw")
fd2 = os.dup(fd.fileno())
os.system("lslocks -p %d" % pid) # one lock
os.system("lslocks -p %d" % pid) # no output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.