Is it possible to clone a file descriptor? I know about dup, but I'd like to have a file descriptor which has a separate state (position), as if I opened the same file again, with the same flags (the problem with re-opening is that a) I have to store file path, which is not needed currently in my code and b) If the file has been deleted, I cannot re-open it).
If it is not possible, then my idea is to use dup, and pread/pwrite, so I manage file position myself. Are there any drawbacks of this idea?
I don't believe there is a single library function or system call that will do what you want on Linux. But you can do the following:
readlink(3) or realpath(3) on the file /proc/self/fd/<X>, where <X> is the file descriptor you want to duplicate. This returns the full path to the file in question.open(2) to get a brand new descriptor for that file.read(2)s and write(2)s are independent.This gets around your concern about storing the file path, by just getting it dynamically when needed.
I don't understand your second point, though, the one about deleting the file. If this process deletes the file, why would you want to create a duplicate descriptor for it? Regardless, if either this or another process deletes the file, then the file is still accessible until the file descriptor itself is closed anyway. Doing the duplication as I described above should be valid until every open descriptor referring to the file is closed. (Although you won't be able to use the link /proc/self/fd/<X> if this process deletes the file and closes its descriptor. You'll need another way of recovering the filename from the file descriptor. But in that case, the question doesn't make much sense as you no longer have a valid descriptor to duplicate anyway!)
Also, creating a second, independent file descriptor seems like a bit of a strange design choice to me. I'd probably just go with lseek(2) + read(2) or pread(2). I don't see any special drawbacks to that approach, other than needing to manage different file positions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With