Exclusive File Creation With create_new
File::create_new fails with ErrorKind::AlreadyExists when the path exists, giving you race-free exclusive creation for lock files and IDs.
Code
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let path = "session.lock";
// create_new 等价于 O_CREAT | O_EXCL:已存在即失败,绝不覆盖
match File::create_new(path) {
Ok(_) => println!("lock acquired: {path}"),
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
println!("lock held by someone else: {path}");
}
Err(err) => println!("unexpected: {err}"),
}
// 清理演示产物,示例可重复运行
std::fs::remove_file(path).ok();
}Exclusive creation
File::create_new maps to O_CREAT | O_EXCL: it succeeds only when the path does not exist, failing with ErrorKind::AlreadyExists otherwise. The match prints lock acquired or lock held by someone else accordingly — no check-then-create race window exists.
Cleanup for reruns
std::fs::remove_file(path).ok() deletes the demo artifact so the example runs repeatedly: the first run acquires, later runs report the lock held until cleaned.
Where this applies
Lock files, singleton markers, and one-time IDs all need the create-only-if-absent semantic; create_new provides it atomically at the OS layer.
Interactive Tools for This Topic
FAQ
- What guarantee does create_new give that create does not?
- create truncates an existing file; create_new fails with AlreadyExists when the path exists, making exclusive creation race-free.
- Why is the cleanup line written with .ok()?
- remove_file returns a Result; .ok() discards the error so a missing file on rerun does not panic the demo.
Report a problem with this exampleOpens a pre-filled issue on GitHub.