1use std::{
7 fmt,
8 fs::{self, File, OpenOptions},
9 io::{self, Read},
10 path::{Path, PathBuf},
11};
12
13use super::Limit;
14use crate::{Error, Result, parse::pid_file, sys};
15
16const DEFAULT_UMASK: u32 = 0o027;
18const DEFAULT_OPEN_FILES_TARGET: u64 = 65_536;
20const DEFAULT_OPEN_FILES_MINIMUM: u64 = 1_024;
22
23pub fn guard(name: &str) -> Result<Guard> {
63 Guard::builder(name).build()
64}
65
66#[must_use = "dropping the guard releases the single-instance lock"]
76pub struct Guard {
77 lock: Option<File>,
79 report: GuardReport,
80}
81
82impl Guard {
83 pub fn builder(name: &str) -> GuardBuilder {
98 GuardBuilder {
99 name: name.to_owned(),
100 lock_dir: None,
101 lock: true,
102 allow_network_lock: false,
103 umask: Some(DEFAULT_UMASK),
104 open_files_target: DEFAULT_OPEN_FILES_TARGET,
105 open_files_minimum: DEFAULT_OPEN_FILES_MINIMUM,
106 }
107 }
108
109 #[must_use]
111 pub fn report(&self) -> &GuardReport {
112 &self.report
113 }
114
115 #[must_use]
117 pub fn lock_file(&self) -> Option<&Path> {
118 self.report.lock_file.as_deref()
119 }
120
121 #[must_use]
137 pub fn is_held(&self) -> bool {
138 match (&self.lock, &self.report.lock_file) {
139 (Some(file), Some(path)) => same_file(file, path),
140 _ => false,
141 }
142 }
143}
144
145impl fmt::Debug for Guard {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.debug_struct("Guard")
148 .field("report", &self.report)
149 .finish()
150 }
151}
152
153#[derive(Clone, Debug)]
155pub struct GuardBuilder {
156 name: String,
157 lock_dir: Option<PathBuf>,
158 lock: bool,
159 allow_network_lock: bool,
160 umask: Option<u32>,
161 open_files_target: u64,
162 open_files_minimum: u64,
163}
164
165impl GuardBuilder {
166 #[must_use]
172 pub fn lock_dir(mut self, dir: impl Into<PathBuf>) -> Self {
173 self.lock_dir = Some(dir.into());
174 self
175 }
176
177 #[must_use]
180 pub fn lock(mut self, on: bool) -> Self {
181 self.lock = on;
182 self
183 }
184
185 #[must_use]
188 pub fn allow_network_lock(mut self, on: bool) -> Self {
189 self.allow_network_lock = on;
190 self
191 }
192
193 #[must_use]
195 pub fn umask(mut self, mask: u32) -> Self {
196 self.umask = Some(mask & 0o777);
197 self
198 }
199
200 #[must_use]
202 pub fn keep_umask(mut self) -> Self {
203 self.umask = None;
204 self
205 }
206
207 #[must_use]
210 pub fn open_files_target(mut self, n: u64) -> Self {
211 self.open_files_target = n;
212 self
213 }
214
215 #[must_use]
218 pub fn open_files_minimum(mut self, n: u64) -> Self {
219 self.open_files_minimum = n;
220 self
221 }
222
223 pub fn build(self) -> Result<Guard> {
225 validate_name(&self.name)?;
226 let mut warnings = Vec::new();
227
228 let files_before = sys::open_files_limit()?;
230 let raise_to = plan_open_files(
231 files_before,
232 self.open_files_target,
233 self.open_files_minimum,
234 sys::open_files_ceiling(),
235 )?;
236
237 let (lock, lock_file, lock_filesystem) = if self.lock {
238 let dir = match &self.lock_dir {
239 Some(d) => {
240 create_owner_only(d)?;
241 d.clone()
242 }
243 None => default_dir(&self.name)?,
244 };
245 check_dir(&dir)?;
246 let fs_kind = sys::filesystem(&dir);
247 if let Some(kind) = fs_kind.filter(|k| k.network) {
248 if !self.allow_network_lock {
249 return Err(unavailable(
250 &dir,
251 io::ErrorKind::Unsupported,
252 &format!(
253 "it is on a {} filesystem, where locks may not hold across machines; use a local \
254 directory, or allow_network_lock(true)",
255 kind.name
256 ),
257 ));
258 }
259 warnings.push(GuardWarning::NetworkLockAllowed {
260 filesystem: kind.name,
261 });
262 }
263 let lock_path = dir.join(format!("{}.lock", self.name));
264 let pid_path = dir.join(format!("{}.pid", self.name));
265 let file = lock_file(&dir, &lock_path, &pid_path)?;
266 path_lib::write_atomic(&pid_path, format!("{}\n", std::process::id())).map_err(
267 |e| {
268 unavailable(
269 &dir,
270 io::ErrorKind::Other,
271 &format!("the pid file cannot be written: {e}"),
272 )
273 },
274 )?;
275 (Some(file), Some(lock_path), fs_kind.map(|k| k.name))
276 } else {
277 warnings.push(GuardWarning::LockDisabled);
278 (None, None, None)
279 };
280
281 let files_after = match raise_to {
282 Some(n) => {
283 sys::set_open_files_soft(n)?;
284 sys::open_files_limit()?
285 }
286 None => files_before,
287 };
288
289 let (umask_before, umask_after) = match self.umask {
290 Some(mask) => {
291 let before = sys::swap_umask(mask);
292 (before, before.map(|_| mask))
293 }
294 None => {
295 let current = sys::swap_umask(0o077);
297 if let Some(c) = current {
298 sys::swap_umask(c);
299 }
300 (current, current)
301 }
302 };
303
304 #[cfg(unix)]
308 if let Some(threads) = sys::thread_count().filter(|&n| n > 1) {
309 warnings.push(GuardWarning::ThreadsAlreadyRunning { threads });
310 }
311
312 Ok(Guard {
313 lock,
314 report: GuardReport {
315 lock_file,
316 lock_filesystem,
317 umask_before,
318 umask_after,
319 open_files_before: files_before,
320 open_files_after: files_after,
321 warnings,
322 },
323 })
324 }
325}
326
327#[derive(Clone, Debug, PartialEq, Eq)]
329#[non_exhaustive]
330pub struct GuardReport {
331 pub lock_file: Option<PathBuf>,
333 pub lock_filesystem: Option<&'static str>,
335 pub umask_before: Option<u32>,
337 pub umask_after: Option<u32>,
339 pub open_files_before: Limit,
341 pub open_files_after: Limit,
343 pub warnings: Vec<GuardWarning>,
345}
346
347#[derive(Clone, Debug, PartialEq, Eq)]
349#[non_exhaustive]
350pub enum GuardWarning {
351 ThreadsAlreadyRunning {
355 threads: usize,
357 },
358 NetworkLockAllowed {
361 filesystem: &'static str,
363 },
364 LockDisabled,
366}
367
368fn validate_name(name: &str) -> Result<()> {
370 let ok = !name.is_empty()
371 && name.len() <= 64
372 && !name.starts_with('.')
373 && name
374 .bytes()
375 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
376 if ok {
377 Ok(())
378 } else {
379 Err(Error::InvalidInput {
380 what: "process guard name",
381 reason: "use 1 to 64 ASCII letters, digits, '-', '_', or '.', not starting with '.'",
382 })
383 }
384}
385
386fn plan_open_files(
389 before: Limit,
390 target: u64,
391 minimum: u64,
392 ceiling: Option<u64>,
393) -> Result<Option<u64>> {
394 if before.soft.is_none() && before.hard.is_none() {
395 return Ok(None); }
397 let hard = before.hard.unwrap_or(u64::MAX);
398 let usable = hard.min(ceiling.unwrap_or(u64::MAX));
399 if usable < minimum {
400 return Err(Error::OpenFilesTooLow {
401 have: usable,
402 need: minimum,
403 });
404 }
405 let want = target.max(minimum).min(usable);
406 Ok((before.soft.unwrap_or(u64::MAX) < want).then_some(want))
407}
408
409fn unavailable(dir: &Path, kind: io::ErrorKind, reason: &str) -> Error {
410 Error::RunDirUnavailable {
411 path: dir.to_path_buf(),
412 source: io::Error::new(kind, reason.to_owned()),
413 }
414}
415
416fn lock_file(dir: &Path, lock_path: &Path, pid_path: &Path) -> Result<File> {
420 for _ in 0..LOCK_ATTEMPTS {
421 let file = open_lock_file(dir, lock_path)?;
422 match file.try_lock() {
423 Ok(()) => {}
424 Err(fs::TryLockError::WouldBlock) => {
425 return Err(Error::AlreadyRunning {
426 pid: read_pid(pid_path),
427 lock_file: lock_path.to_path_buf(),
428 });
429 }
430 Err(fs::TryLockError::Error(e)) => {
431 return Err(Error::Io {
432 what: "the process guard's lock",
433 source: e,
434 });
435 }
436 }
437 if same_file(&file, lock_path) {
438 return Ok(file);
439 }
440 }
441 Err(unavailable(
442 dir,
443 io::ErrorKind::Interrupted,
444 "the lock file keeps being replaced while it is locked; find what removes it",
445 ))
446}
447
448const LOCK_ATTEMPTS: usize = 3;
450
451fn same_file(file: &File, path: &Path) -> bool {
453 #[cfg(unix)]
454 {
455 use std::os::unix::fs::MetadataExt;
456 match (file.metadata(), fs::symlink_metadata(path)) {
457 (Ok(a), Ok(b)) => (a.dev(), a.ino()) == (b.dev(), b.ino()),
458 _ => false,
459 }
460 }
461 #[cfg(not(unix))]
462 {
463 let _ = file;
466 fs::symlink_metadata(path).is_ok()
467 }
468}
469
470#[cfg(unix)]
472fn default_dir(name: &str) -> Result<PathBuf> {
473 let Some(uid) = sys::effective_uid() else {
474 return runtime_dir(name);
475 };
476 let dir = if uid == 0 {
477 system_run_dir().join(name)
478 } else {
479 let home = sys::home_dir(uid).ok_or_else(|| {
480 unavailable(
481 Path::new(name),
482 io::ErrorKind::NotFound,
483 &format!(
484 "user {uid} has no home directory in the account database for the default lock; pass lock_dir"
485 ),
486 )
487 })?;
488 user_run_dir(&home, name)
489 };
490 create_owner_only(&dir)?;
491 Ok(dir)
492}
493
494#[cfg(not(unix))]
495fn default_dir(name: &str) -> Result<PathBuf> {
496 runtime_dir(name)
498}
499
500#[cfg(unix)]
502fn system_run_dir() -> &'static Path {
503 if cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/run").is_dir() {
504 Path::new("/run")
505 } else {
506 Path::new("/var/run")
507 }
508}
509
510#[cfg(unix)]
512fn user_run_dir(home: &Path, name: &str) -> PathBuf {
513 if cfg!(any(target_os = "macos", target_os = "ios")) {
514 home.join("Library/Application Support")
515 .join(name)
516 .join("run")
517 } else {
518 home.join(".local/state").join(name).join("run")
519 }
520}
521
522fn runtime_dir(name: &str) -> Result<PathBuf> {
523 let app = path_lib::App::new(name)
524 .map_err(|e| unavailable(Path::new(name), io::ErrorKind::InvalidInput, &e.to_string()))?;
525 let dir = app.dir(path_lib::Kind::Runtime).to_path_buf();
526 app.ensure(path_lib::Kind::Runtime).map_err(|e| {
527 unavailable(
528 &dir,
529 io::ErrorKind::Other,
530 &format!("it cannot be created: {e}"),
531 )
532 })?;
533 Ok(dir)
534}
535
536fn create_owner_only(dir: &Path) -> Result<()> {
537 if fs::symlink_metadata(dir).is_ok() {
538 return Ok(());
539 }
540 let mut builder = fs::DirBuilder::new();
541 builder.recursive(true);
542 #[cfg(unix)]
543 {
544 use std::os::unix::fs::DirBuilderExt;
545 builder.mode(0o700);
546 }
547 builder
548 .create(dir)
549 .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}")))
550}
551
552fn check_dir(dir: &Path) -> Result<()> {
554 let meta = fs::symlink_metadata(dir)
555 .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be read: {e}")))?;
556 if meta.file_type().is_symlink() {
557 return Err(unavailable(
558 dir,
559 io::ErrorKind::InvalidInput,
560 "it is a symbolic link; use the real directory",
561 ));
562 }
563 if !meta.is_dir() {
564 return Err(unavailable(
565 dir,
566 io::ErrorKind::InvalidInput,
567 "it is not a directory",
568 ));
569 }
570 #[cfg(unix)]
571 {
572 use std::os::unix::fs::MetadataExt;
573 if meta.mode() & 0o022 != 0 {
574 return Err(unavailable(
575 dir,
576 io::ErrorKind::PermissionDenied,
577 "other users can write to it and could replace the lock file; chmod 700 it, or use another directory",
578 ));
579 }
580 if sys::effective_uid().is_some_and(|uid| uid != meta.uid()) {
581 return Err(unavailable(
582 dir,
583 io::ErrorKind::PermissionDenied,
584 "it belongs to another user; use a directory this user owns",
585 ));
586 }
587 }
588 #[cfg(windows)]
589 {
590 use std::os::windows::fs::MetadataExt;
591 if meta.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
592 return Err(unavailable(
593 dir,
594 io::ErrorKind::InvalidInput,
595 "it is a junction or link; use the real directory",
596 ));
597 }
598 }
599 Ok(())
600}
601
602fn open_lock_file(dir: &Path, path: &Path) -> Result<File> {
604 if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
605 return Err(unavailable(
606 dir,
607 io::ErrorKind::InvalidInput,
608 "the lock file is a symbolic link; remove it",
609 ));
610 }
611 let mut options = OpenOptions::new();
612 options.read(true).write(true).create(true).truncate(false);
613 sys::lock_open_options(&mut options);
614 let file = options.open(path).map_err(|e| {
615 unavailable(
616 dir,
617 e.kind(),
618 &format!("the lock file cannot be opened: {e}"),
619 )
620 })?;
621 let opened = file
622 .metadata()
623 .map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
624 let at_path =
625 fs::symlink_metadata(path).map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
626 if !opened.is_file() || at_path.file_type().is_symlink() {
627 return Err(unavailable(
628 dir,
629 io::ErrorKind::InvalidInput,
630 "the lock file is not a regular file; remove it",
631 ));
632 }
633 #[cfg(unix)]
634 {
635 use std::os::unix::fs::MetadataExt;
636 if (opened.dev(), opened.ino()) != (at_path.dev(), at_path.ino()) {
638 return Err(unavailable(
639 dir,
640 io::ErrorKind::InvalidInput,
641 "the lock file changed while it was opened",
642 ));
643 }
644 if sys::effective_uid().is_some_and(|uid| uid != opened.uid()) {
645 return Err(unavailable(
646 dir,
647 io::ErrorKind::PermissionDenied,
648 "the lock file belongs to another user; remove it",
649 ));
650 }
651 }
652 #[cfg(windows)]
653 {
654 use std::os::windows::fs::MetadataExt;
655 if opened.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
656 return Err(unavailable(
657 dir,
658 io::ErrorKind::InvalidInput,
659 "the lock file is a link; remove it",
660 ));
661 }
662 }
663 Ok(file)
664}
665
666fn read_pid(path: &Path) -> Option<u32> {
668 let mut data = Vec::with_capacity(pid_file::MAX_BYTES + 1);
669 File::open(path)
670 .ok()?
671 .take(pid_file::MAX_BYTES as u64 + 1)
672 .read_to_end(&mut data)
673 .ok()?;
674 pid_file::parse(&data)
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680
681 fn temp_dir(tag: &str) -> PathBuf {
682 let dir = std::env::temp_dir().join(format!("sys-lib-guard-{tag}-{}", std::process::id()));
683 let _ = fs::remove_dir_all(&dir);
684 dir
685 }
686
687 #[test]
688 fn test_guard_name_validation() {
689 for good in ["site", "my-app", "a.b_c", "x"] {
690 assert!(validate_name(good).is_ok(), "{good}");
691 }
692 for bad in [
693 "",
694 ".hidden",
695 "a/b",
696 "a\\b",
697 "..",
698 "sp ace",
699 "naïve",
700 &"x".repeat(65),
701 ] {
702 assert!(
703 matches!(validate_name(bad), Err(Error::InvalidInput { .. })),
704 "{bad:?}"
705 );
706 }
707 }
708
709 #[test]
710 fn test_guard_open_files_plan() {
711 let limit = |soft, hard| Limit { soft, hard };
712 assert_eq!(
714 plan_open_files(limit(Some(1024), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
715 Some(65_536)
716 );
717 assert_eq!(
718 plan_open_files(limit(Some(1024), Some(4096)), 65_536, 1_024, None).unwrap(),
719 Some(4096)
720 );
721 assert_eq!(
723 plan_open_files(limit(Some(100_000), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
724 None
725 );
726 assert_eq!(
728 plan_open_files(limit(Some(256), None), 65_536, 1_024, Some(24_576)).unwrap(),
729 Some(24_576)
730 );
731 let e = plan_open_files(limit(Some(256), Some(512)), 65_536, 1_024, None).unwrap_err();
733 assert!(matches!(
734 e,
735 Error::OpenFilesTooLow {
736 have: 512,
737 need: 1_024
738 }
739 ));
740 assert_eq!(
742 plan_open_files(limit(None, None), 65_536, 1_024, None).unwrap(),
743 None
744 );
745 }
746
747 #[test]
748 fn test_guard_locks_and_a_second_guard_is_refused() {
749 let dir = temp_dir("second");
750 let first = Guard::builder("guard-test")
751 .lock_dir(&dir)
752 .keep_umask()
753 .open_files_target(0)
754 .open_files_minimum(0)
755 .build()
756 .unwrap();
757 let lock = first.lock_file().unwrap().to_path_buf();
758 assert!(lock.ends_with("guard-test.lock"));
759 assert_eq!(
760 read_pid(&dir.join("guard-test.pid")),
761 Some(std::process::id())
762 );
763 let second = Guard::builder("guard-test")
764 .lock_dir(&dir)
765 .keep_umask()
766 .open_files_target(0)
767 .open_files_minimum(0)
768 .build();
769 match second {
770 Err(Error::AlreadyRunning { pid, lock_file }) => {
771 assert_eq!(pid, Some(std::process::id()));
772 assert_eq!(lock_file, lock);
773 }
774 other => panic!("expected AlreadyRunning, got {other:?}"),
775 }
776 drop(first);
777 assert!(lock.exists());
779 let again = Guard::builder("guard-test")
780 .lock_dir(&dir)
781 .keep_umask()
782 .open_files_target(0)
783 .open_files_minimum(0)
784 .build();
785 assert!(again.is_ok());
786 drop(again);
787 let _ = fs::remove_dir_all(&dir);
788 }
789
790 #[test]
791 fn test_guard_is_held_until_the_lock_file_is_replaced() {
792 let dir = temp_dir("held");
795 let g = Guard::builder("held")
796 .lock_dir(&dir)
797 .keep_umask()
798 .open_files_target(0)
799 .open_files_minimum(0)
800 .build()
801 .unwrap();
802 assert!(g.is_held());
803 let lock = g.lock_file().unwrap().to_path_buf();
804 let removed = fs::remove_file(&lock);
805 if cfg!(windows) {
806 assert!(removed.is_err(), "a held lock file was deleted");
807 assert!(g.is_held());
808 } else {
809 removed.unwrap();
810 assert!(!g.is_held());
811 fs::write(&lock, b"").unwrap();
812 assert!(!g.is_held(), "a new file at the path is not the locked one");
813 }
814 drop(g);
815 let _ = fs::remove_dir_all(&dir);
816 }
817
818 #[test]
819 fn test_guard_without_lock_is_not_held() {
820 let g = Guard::builder("unheld")
821 .lock(false)
822 .keep_umask()
823 .open_files_target(0)
824 .open_files_minimum(0)
825 .build()
826 .unwrap();
827 assert!(!g.is_held());
828 }
829
830 #[cfg(unix)]
831 #[test]
832 fn test_guard_default_dir_ignores_the_environment() {
833 let uid = sys::effective_uid().unwrap();
835 if uid == 0 {
836 assert!(system_run_dir().is_dir());
837 return;
838 }
839 let Some(home) = sys::home_dir(uid) else {
840 return;
841 };
842 let dir = user_run_dir(&home, "probe");
843 assert!(dir.starts_with(&home));
844 assert!(dir.ends_with("probe/run"));
845 let dir = user_run_dir(Path::new("/h"), "site");
846 if cfg!(target_os = "macos") {
847 assert_eq!(dir, Path::new("/h/Library/Application Support/site/run"));
848 } else {
849 assert_eq!(dir, Path::new("/h/.local/state/site/run"));
850 }
851 }
852
853 #[test]
854 fn test_guard_lock_false_takes_no_lock() {
855 let g = Guard::builder("nolock")
856 .lock(false)
857 .keep_umask()
858 .open_files_target(0)
859 .open_files_minimum(0)
860 .build()
861 .unwrap();
862 assert_eq!(g.lock_file(), None);
863 assert!(g.report().warnings.contains(&GuardWarning::LockDisabled));
864 }
865
866 #[test]
867 fn test_guard_refuses_a_file_as_lock_dir() {
868 let dir = temp_dir("file");
869 fs::create_dir_all(dir.parent().unwrap()).unwrap();
870 fs::write(&dir, b"x").unwrap();
871 let e = Guard::builder("g")
872 .lock_dir(&dir)
873 .keep_umask()
874 .build()
875 .unwrap_err();
876 assert!(matches!(e, Error::RunDirUnavailable { .. }), "{e:?}");
877 let _ = fs::remove_file(&dir);
878 }
879
880 #[cfg(unix)]
881 #[test]
882 fn test_guard_lock_path_is_symlink_refuses() {
883 let dir = temp_dir("symlink");
885 create_owner_only(&dir).unwrap();
886 let target = dir.join("elsewhere");
887 fs::write(&target, b"").unwrap();
888 std::os::unix::fs::symlink(&target, dir.join("g.lock")).unwrap();
889 let e = Guard::builder("g")
890 .lock_dir(&dir)
891 .keep_umask()
892 .build()
893 .unwrap_err();
894 assert!(e.to_string().contains("symbolic link"), "{e}");
895 let _ = fs::remove_dir_all(&dir);
896 }
897
898 #[cfg(unix)]
899 #[test]
900 fn test_guard_world_writable_dir_refuses() {
901 use std::os::unix::fs::PermissionsExt;
903 let dir = temp_dir("writable");
904 create_owner_only(&dir).unwrap();
905 fs::set_permissions(&dir, fs::Permissions::from_mode(0o777)).unwrap();
906 let e = Guard::builder("g")
907 .lock_dir(&dir)
908 .keep_umask()
909 .build()
910 .unwrap_err();
911 assert!(e.to_string().contains("other users can write"), "{e}");
912 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
913 let _ = fs::remove_dir_all(&dir);
914 }
915
916 #[cfg(unix)]
917 #[test]
918 fn test_guard_symlinked_dir_refuses() {
919 let dir = temp_dir("dirlink");
920 let real = temp_dir("dirlink-real");
921 create_owner_only(&real).unwrap();
922 std::os::unix::fs::symlink(&real, &dir).unwrap();
923 let e = Guard::builder("g")
924 .lock_dir(&dir)
925 .keep_umask()
926 .build()
927 .unwrap_err();
928 assert!(e.to_string().contains("symbolic link"), "{e}");
929 let _ = fs::remove_file(&dir);
930 let _ = fs::remove_dir_all(&real);
931 }
932
933 #[test]
934 fn test_guard_stale_pid_file_is_replaced() {
935 let dir = temp_dir("stale");
937 create_owner_only(&dir).unwrap();
938 fs::write(dir.join("g.pid"), b"999999\n").unwrap();
939 let g = Guard::builder("g")
940 .lock_dir(&dir)
941 .keep_umask()
942 .open_files_target(0)
943 .open_files_minimum(0)
944 .build()
945 .unwrap();
946 assert_eq!(read_pid(&dir.join("g.pid")), Some(std::process::id()));
947 drop(g);
948 let _ = fs::remove_dir_all(&dir);
949 }
950
951 #[test]
952 fn test_guard_report_with_threads_warns() {
953 let g = Guard::builder("threads")
956 .lock(false)
957 .keep_umask()
958 .open_files_target(0)
959 .open_files_minimum(0)
960 .build()
961 .unwrap();
962 let warned = g
963 .report()
964 .warnings
965 .iter()
966 .any(|w| matches!(w, GuardWarning::ThreadsAlreadyRunning { .. }));
967 if cfg!(unix) {
968 assert_eq!(warned, sys::thread_count().is_some_and(|n| n > 1));
969 } else {
970 assert!(!warned);
971 }
972 if cfg!(unix) {
973 assert!(g.report().umask_before.is_some());
974 assert_eq!(g.report().umask_before, g.report().umask_after);
975 } else {
976 assert_eq!(g.report().umask_before, None);
977 }
978 }
979}