Best way to hold onto a temp file and directory so it doesn't get automatically cleaned up until later?

⚓ Rust    📅 2026-02-09    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 57 days ago. The information described in this article may have changed.

Hey all,

I've been working on getting my program running and I've converted my previous code to using the tempfile crate. Currently my code is organized like this and I apologize if I completely butcher the explanation:

I'll try to keep some brevity here but if more code is necessary to explain what I'm trying to do, let me know and I'll add it.

main.rs:

[...]
let mut proxy = tor_proxy_controller::start_proxy(pid);

//do proxy things

tor_proxy_controller::delete_arti_bin(proxy);
[...]

tor_proxy_controller.rs:

pub fn start_proxy(pid: u32) -> Result<Child,Error>{
    let arti = temp_file_controller::create_arti_bin(pid);
[...]

temp_file_controller.rs:

pub fn create_arti_bin(pid: u32) -> Result<PathBuf, std::io::Error>{
    let temp_dir = tempdir()?;
    let filename = format!("arti_{}.exe",pid);
    let file = temp_dir.path().join(filename);

    fs::write(&file, ARTI_BYTES)?;

    Ok(file)
}

pub fn delete_arti_bin(bin:Child, dir:TempDir) -> Result<(), Box<dyn std::error::Error>>{
    drop(bin);
    dir.close()?;
    Ok(())
}

I think I know how to keep the temp file and directory around at least until I'm done using it in main. By passing the PathBuf from temp_file_controller to proxy_controller, then passing the resulting Result<Child,Error> to main, I think that keeps everything around and running.

If I'm just returning the file I create within the temporary directory, how can I drop the file and close() the directory from main later on? At that point in main it's a Result<Child,Error> type.

Can I extract out the tempdir from the Child portion of the proxy object and be able to access it that way?

Or is there a way for me to somehow hold onto the PathBuf and TempDir created in temp_file_controller values so that I can just call delete_arti_bin and have the information already held so I don't need to pass anything at all?

I'm also thinking of the future where I'd like to be able to create multiple proxies simultaneously on various ports. Whatever I make here, I'd like to be extendable to handling multiple binaries.

I hope this all makes sense...kind of a stream of consciousness so thank you for your assistance as always.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed