Skip to main content

cleanup_orphans

Function cleanup_orphans 

Source
pub fn cleanup_orphans(max_age_hours: u64) -> Result<usize>
Expand description

Sweep the OS temp directory for default-prefix entries this crate could have created and remove those that look orphaned.

An entry is removed when both of these hold:

  1. The owning process is not alive. Each default-prefix entry carries the originating process’s PID in its basename (.tmp-{pid}-{name} for crate::TempDir, .tmpfile-{pid}-{name} for crate::NamedTempFile). On Linux liveness is checked via the presence of /proc/{pid}. On macOS and Windows the liveness check is treated as “process is dead” (since cross-platform process introspection without platform deps is not available); the age check carries the safety burden alone on those platforms.
  2. The entry’s mtime is at least max_age_hours old. This is the load-bearing safety guard on macOS and Windows: pick a threshold larger than any process you expect to legitimately hold temp paths.

Entries that do not match the crate’s default prefix patterns, including any caller-supplied with_prefix(...) paths, are never touched. Likewise, legacy entries from 0.9.0 and 0.9.1 that predate the PID-in-basename format are ignored: they have no PID segment to parse and are not eligible for cleanup.

§Errors

Returns the underlying io::Error only if reading the OS temp directory itself fails. Per-entry failures (permission denied, entry disappeared between scan and removal, Windows handle still open, etc.) are intentionally silent and not counted in the return value. This matches the silent-Drop ethos for the rest of the crate.

§Returns

The number of entries successfully removed.

§Example

use mod_tempdir::cleanup_orphans;

// At program startup, sweep anything older than 24 hours left
// behind by crashed earlier runs.
let removed = cleanup_orphans(24).unwrap_or(0);
eprintln!("cleanup_orphans removed {removed} orphaned entries");