Skip to content

Commit e7ce03e

Browse files
test(services): write the process shim atomically (#1351) (#1358)
Stages the shim in a temporary file and renames it into place, so the final path is never open for writing while another thread forks. Authored by @ItsAbir005.
2 parents 7fbf164 + 497930d commit e7ce03e

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎crates/nostream-services/src/process.rs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,13 +277,23 @@ mod tests {
277277

278278
/// Writes an executable shell script into `directory` under `name`.
279279
fn shim(directory: &std::path::Path, name: &str, body: &str) -> String {
280+
use std::io::Write;
281+
280282
let path = directory.join(name);
281-
std::fs::write(&path, format!("#!/bin/bash\n{body}\n")).expect("the shim is written");
282-
let mut permissions = std::fs::metadata(&path)
283+
// Write to a uniquely named temp file in the same directory, close the write descriptor,
284+
// mark it executable, and rename it into place so the target path never exists while
285+
// still open for writing (narrows the ETXTBSY fork/exec window across parallel tests).
286+
let mut temp = tempfile::NamedTempFile::new_in(directory).expect("a temporary shim file");
287+
temp.write_all(format!("#!/bin/bash\n{body}\n").as_bytes())
288+
.expect("the shim is written");
289+
let (file, temp_path) = temp.keep().expect("the temporary shim stays");
290+
drop(file);
291+
let mut permissions = std::fs::metadata(&temp_path)
283292
.expect("the shim exists")
284293
.permissions();
285294
permissions.set_mode(0o755);
286-
std::fs::set_permissions(&path, permissions).expect("the shim is executable");
295+
std::fs::set_permissions(&temp_path, permissions).expect("the shim is executable");
296+
std::fs::rename(&temp_path, &path).expect("the shim is moved into place");
287297
path.display().to_string()
288298
}
289299

0 commit comments

Comments
 (0)