How to work with a raw file descriptor without automatically closing the fd

I am working on a LD_PRELOAD wrapper for some glbc API.
So it gets access to raw dirfd(file descriptors of a directory).

I need to read/get the full path associated with the "dirfd", but should not close or do anything else to the dirfd.

How do I do that?

I see
But this states

This function consumes ownership of the specified file descriptor. The returned object will take responsibility for closing it when the object goes out of scope.

That means, as I understand it, that I can turn dirfd into maybe a "File" handle and use metadata or something to get at the path assocaited with the dirfd.

But when the file handle goes out of scope, the dirfd wikll get closed.

Is there another way of doing this without closing or doing anything else dirfd?

You can forget the File after using it, to prevent it from closing the file descriptor.

Interesting. And this will not leak memory?
I dont want to touch the FD, But the File object would have been allocated on heap. And will it linger and cause a memory leak?

Takes ownership and "forgets" about the value  **without running its destructor** .

Any resources the value manages, such as heap memory or a file handle, will linger forever in an unreachable state. However, it does not guarantee that pointers to this memory will remain valid.

But I also see this example in there.

The canonical safe use of mem::forget is to circumvent a value's destructor implemented by the Drop trait. For example, this will leak a File, i.e. reclaim the space taken by the variable but never close the underlying system resource:

use std::mem;
use std::fs::File;

let file = File::open("foo.txt").unwrap();
This is useful when the ownership of the underlying resource was previously transferred to code outside of Rust, for example by transmitting the raw file descriptor to C code.

So according to the example in there. Looks like this is the right solution.
I just want to confirm that this will not leak memory before I mark this a Solution

So the 2 are contradicting and confusing

I usually just wrap things with ManuallyDrop and call it a day.

A wrapper to inhibit compiler from automatically calling T ’s destructor. This wrapper is 0-cost.

File in Rust is a very lightweight wrapper around a file descriptor. It does not allocate or free any memory on its own, and passing a File to mem::forget will not leak any memory.

If you have placed a File into some wrapper or container that does allocate heap memory, like BufReader<File> or Box<File>, then you should move it out of that wrapper before forgetting it.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.