1#![deny(unsafe_code)]
64
65#[cfg(target_os = "macos")]
66mod darwin_user_temp;
67#[cfg(target_os = "macos")]
68pub use darwin_user_temp::darwin_user_temp_dir;
69
70#[cfg(windows)]
71mod profile;
72#[cfg(windows)]
73pub use profile::profile_dir;
74
75#[cfg(unix)]
76mod user_home;
77#[cfg(unix)]
78pub use user_home::{effective_uid, real_user_home_dir};
79
80#[cfg(unix)]
81pub mod admission_gate;
82pub mod boot_id;
83#[cfg(unix)]
84pub mod child_exit;
85pub mod child_spawn;
86#[cfg(target_os = "macos")]
87pub mod code_signature;
88pub mod config_keychain;
89mod durable_replace;
90#[cfg(any(unix, windows))]
91mod retained_file;
92#[cfg(any(target_os = "linux", target_os = "macos", windows))]
93mod retained_replace;
94#[cfg(windows)]
95pub use durable_replace::durable_move_to_new_name;
96#[cfg(feature = "test-support")]
97pub use durable_replace::durable_replace_with_rename_hook;
98pub use durable_replace::{durable_replace, DurableReplaceError};
99#[cfg(any(unix, windows))]
100pub use retained_file::{
101 open_directory_nofollow_all, open_regular_nofollow, open_regular_nofollow_all,
102 retained_file_identity, OpenRegularError, RetainedFileIdentity,
103};
104#[cfg(windows)]
105pub use retained_file::{retained_file_index, WindowsFileIndexIdentity};
106#[cfg(any(target_os = "linux", target_os = "macos", windows))]
107pub use retained_replace::{
108 create_directory_nofollow_at, open_directory_nofollow_at, open_single_link_file_nofollow_at,
109 OpenRetainedError, RetainedTempFile,
110};
111#[cfg(all(unix, feature = "test-support"))]
112pub mod fork_exec_test;
113pub mod host;
114pub mod launch_nonce;
115pub mod local_peer;
116#[cfg(windows)]
117mod loopback_connect;
118#[cfg(windows)]
119pub use loopback_connect::connect_loopback;
120pub mod named_pipe;
121pub mod privacy_identity;
122mod private_directory;
123#[cfg(unix)]
124pub mod process_group;
125pub mod process_identity;
126pub use private_directory::create_private_directory_exclusive;
127pub mod registration_channel;
128pub mod script_pipe;
129pub mod socket_peer;
130#[cfg(windows)]
131pub mod user_path;
132#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
133pub mod windows_acl;
134#[cfg(unix)]
135pub use launch_nonce::LaunchNonceHandoff;
136pub use launch_nonce::{
137 launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
138 LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
139};
140
141#[cfg(windows)]
142pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
143
144pub use registration_channel::{
145 registration_refusal, supervised, take_registration_channel, RegistrationChannel,
146 RegistrationChannelError, RegistrationRefusal,
147};
148
149#[cfg(target_os = "linux")]
150mod linux;
151#[cfg(target_os = "macos")]
152mod macos;
153
154#[cfg(target_os = "macos")]
155pub use macos::owned_child_start_time;
156#[cfg(windows)]
157mod windows;
158#[cfg(all(test, windows))]
159mod windows_tests;
160#[cfg(windows)]
161pub use windows::{
162 ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
163};
164
165#[cfg(target_os = "linux")]
166use linux as platform;
167#[cfg(target_os = "macos")]
168use macos as platform;
169
170use std::{io, path::Path};
171
172pub const PROCESS_IDENTITY_SUPPORTED: bool =
174 cfg!(any(target_os = "linux", target_os = "macos", windows));
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub struct FileIdentity {
180 pub device: u64,
181 pub inode: u64,
182}
183
184pub fn file_identity(path: &Path) -> Option<FileIdentity> {
187 #[cfg(unix)]
188 {
189 use std::os::unix::fs::MetadataExt;
190
191 std::fs::metadata(path).ok().map(|metadata| FileIdentity {
192 device: metadata.dev(),
193 inode: metadata.ino(),
194 })
195 }
196 #[cfg(not(unix))]
197 {
198 let _ = path;
199 None
200 }
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub struct Observation {
206 pub start_time: u64,
211 pub executable: Option<FileIdentity>,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum ExecutableAccess {
223 Readable,
224 PermissionDenied,
225 Unavailable,
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230pub enum Signal {
231 Terminate,
233 Kill,
235}
236
237pub fn start_time(pid: u32) -> Option<u64> {
241 #[cfg(any(target_os = "linux", target_os = "macos"))]
242 {
243 platform::start_time(pid)
244 }
245 #[cfg(windows)]
246 {
247 Process::open(pid)
248 .ok()??
249 .observe()
250 .map(|observation| observation.start_time)
251 }
252 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
253 {
254 let _ = pid;
255 None
256 }
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub(crate) enum IdentityRead {
262 Alive(u64),
263 #[cfg_attr(windows, allow(dead_code))]
264 Gone,
266 Unknown,
267}
268
269#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
270mod identity_read_tests {
271 use super::*;
272
273 #[test]
274 fn identity_probe_distinguishes_alive_gone_and_invalid() {
275 let mut child = std::process::Command::new("/bin/sh")
276 .args(["-c", "exit 0"])
277 .spawn()
278 .unwrap();
279 let pid = child.id();
280 let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
281 while read_identity(pid) != IdentityRead::Gone {
282 assert!(
283 std::time::Instant::now() < until,
284 "an exited owned child must become gone before reaping"
285 );
286 std::thread::yield_now();
287 }
288 child.wait().unwrap();
289 assert_eq!(
290 read_identity(pid),
291 IdentityRead::Gone,
292 "a missing owned PID is gone"
293 );
294 assert_eq!(read_identity(0), IdentityRead::Unknown);
295 assert!(matches!(
296 read_identity(std::process::id()),
297 IdentityRead::Alive(_)
298 ));
299 }
300}
301
302#[cfg(not(windows))]
303fn read_identity(pid: u32) -> IdentityRead {
304 #[cfg(any(target_os = "linux", target_os = "macos"))]
305 {
306 platform::read_identity(pid)
307 }
308 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
309 {
310 start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
311 }
312}
313
314mod process_tree;
315pub use process_tree::{ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
316
317pub fn process_start_time_ms(pid: u32) -> Option<u64> {
325 start_time_ms_from_native(start_time(pid)?)
326}
327
328fn start_time_ms_from_native(raw: u64) -> Option<u64> {
329 #[cfg(target_os = "linux")]
330 {
331 linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
332 }
333 #[cfg(target_os = "macos")]
334 {
335 Some(raw / 1_000)
336 }
337 #[cfg(windows)]
338 {
339 (raw / 10_000).checked_sub(11_644_473_600_000)
340 }
341 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
342 {
343 let _ = raw;
344 None
345 }
346}
347
348#[cfg(target_os = "linux")]
349fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
350 let boot = read_boot()?
354 .lines()
355 .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
356 boot.checked_mul(1_000)?
357 .checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
358}
359
360#[cfg(all(test, target_os = "linux"))]
361#[test]
362fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
363 let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
364 let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
365 assert_eq!(after - before, 2_000);
366}
367
368pub fn process_start_time_precision_ms() -> u64 {
370 #[cfg(target_os = "linux")]
371 {
372 1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
373 }
374 #[cfg(not(target_os = "linux"))]
375 {
376 1
377 }
378}
379
380pub fn parent_pid(pid: u32) -> Option<u32> {
383 #[cfg(any(target_os = "linux", target_os = "macos"))]
384 {
385 platform::parent_pid(pid)
386 }
387 #[cfg(windows)]
388 {
389 windows::parent_pid(pid)
390 }
391 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
392 {
393 let _ = pid;
394 None
395 }
396}
397
398pub const RESOURCE_USAGE_SUPPORTED: bool =
402 cfg!(any(target_os = "linux", target_os = "macos", windows));
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub enum MemoryKind {
408 PhysFootprint,
412 ResidentSet,
416 WindowsWorkingSet,
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub struct ResourceUsage {
427 pub memory_bytes: u64,
429 pub memory_kind: MemoryKind,
430 pub swap_bytes: Option<u64>,
433 pub cpu_user: std::time::Duration,
435 pub cpu_system: std::time::Duration,
437}
438
439pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
451 #[cfg(any(target_os = "linux", target_os = "macos"))]
452 {
453 platform::resource_usage(pid)
454 }
455 #[cfg(windows)]
456 {
457 Process::open(pid).ok()??.resource_usage()
458 }
459 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
460 {
461 let _ = pid;
462 None
463 }
464}
465
466#[derive(Debug)]
468pub struct Process {
469 pid: u32,
470 #[cfg(target_os = "linux")]
471 pidfd: Option<std::os::fd::OwnedFd>,
472 #[cfg(windows)]
473 handle: std::os::windows::io::OwnedHandle,
474}
475
476impl Process {
477 pub fn open(pid: u32) -> io::Result<Option<Self>> {
487 #[cfg(target_os = "linux")]
488 {
489 linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
490 }
491 #[cfg(target_os = "macos")]
492 {
493 Ok(platform::exists(pid).then_some(Self { pid }))
494 }
495 #[cfg(windows)]
496 {
497 windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
498 }
499 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
500 {
501 let _ = pid;
502 Err(io::Error::new(
503 io::ErrorKind::Unsupported,
504 "process identity is not available on this platform",
505 ))
506 }
507 }
508
509 pub fn pid(&self) -> u32 {
510 self.pid
511 }
512
513 pub fn signals_through_pidfd(&self) -> bool {
516 #[cfg(target_os = "linux")]
517 {
518 self.pidfd.is_some()
519 }
520 #[cfg(not(target_os = "linux"))]
521 {
522 false
523 }
524 }
525
526 pub fn observe(&self) -> Option<Observation> {
530 self.observe_with_executable_access()
531 .map(|(observed, _)| observed)
532 }
533
534 pub fn is_alive_but_unobservable(&self) -> bool {
538 #[cfg(target_os = "linux")]
539 {
540 linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
541 }
542 #[cfg(not(target_os = "linux"))]
543 {
544 false
545 }
546 }
547
548 pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
552 #[cfg(any(target_os = "linux", target_os = "macos"))]
553 {
554 #[cfg(target_os = "linux")]
555 if !linux::pidfd_alive(self.pidfd.as_ref()) {
556 return None;
557 }
558 let start_time = platform::start_time(self.pid)?;
559 #[cfg(target_os = "linux")]
560 let (executable, access) = match linux::executable_identity(self.pid) {
561 Ok(identity) => (Some(identity), ExecutableAccess::Readable),
562 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
563 (None, ExecutableAccess::PermissionDenied)
564 }
565 Err(_) => (None, ExecutableAccess::Unavailable),
566 };
567 #[cfg(target_os = "macos")]
568 let executable = macos::executable_identity(self.pid);
569 #[cfg(target_os = "macos")]
570 let access = if executable.is_some() {
571 ExecutableAccess::Readable
572 } else {
573 ExecutableAccess::Unavailable
574 };
575 Some((
576 Observation {
577 start_time,
578 executable,
579 },
580 access,
581 ))
582 }
583 #[cfg(windows)]
584 {
585 windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
586 }
587 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
588 {
589 None
590 }
591 }
592
593 #[cfg(windows)]
596 pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
597 windows::wait(self, timeout)
598 }
599
600 #[cfg(windows)]
604 pub fn force_stop(
605 &self,
606 expected_start_time: u64,
607 timeout: std::time::Duration,
608 ) -> io::Result<bool> {
609 windows::force_stop(self, expected_start_time, timeout)
610 }
611
612 #[cfg(windows)]
617 pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
618 windows::terminate_with_exit_code(self, exit_code)
619 }
620
621 #[cfg(windows)]
623 pub fn resource_usage(&self) -> Option<ResourceUsage> {
624 windows::resource_usage(self)
625 }
626
627 #[cfg(windows)]
630 pub fn cumulative_cpu_ms(&self) -> Option<u64> {
631 windows::cumulative_cpu_ms(self)
632 }
633
634 pub fn signal(&self, signal: Signal) -> io::Result<bool> {
648 #[cfg(any(target_os = "linux", target_os = "macos"))]
649 {
650 #[cfg(target_os = "linux")]
651 let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
652 #[cfg(target_os = "macos")]
653 let result = macos::signal(self.pid, signal);
654 match result {
655 Ok(()) => Ok(true),
656 Err(rustix::io::Errno::SRCH) => Ok(false),
657 Err(error) => Err(error.into()),
658 }
659 }
660 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
661 {
662 let _ = signal;
663 Err(io::Error::new(
664 io::ErrorKind::Unsupported,
665 "process signalling is not available on this platform",
666 ))
667 }
668 }
669}
670
671#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
672mod tests {
673 use std::{
674 io::Read,
675 process::{Child, Command, Stdio},
676 time::{Duration, Instant},
677 };
678
679 use super::*;
680
681 fn spawn_sleep() -> Child {
682 Command::new("sleep")
683 .arg("60")
684 .spawn()
685 .expect("spawn sleep")
686 }
687
688 fn sleep_identity() -> FileIdentity {
690 let path = ["/bin/sleep", "/usr/bin/sleep"]
691 .into_iter()
692 .find(|path| Path::new(path).exists())
693 .expect("sleep is installed");
694 file_identity(Path::new(path)).expect("stat sleep")
695 }
696
697 fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
700 let deadline = Instant::now() + Duration::from_secs(5);
701 loop {
702 let observation = process.observe().expect("child is alive");
703 if observation.executable == Some(expected) || Instant::now() > deadline {
704 return observation;
705 }
706 std::thread::sleep(Duration::from_millis(10));
707 }
708 }
709
710 #[test]
711 fn own_process_is_observable_with_its_own_image() {
712 let process = Process::open(std::process::id())
713 .expect("open own process")
714 .expect("own process exists");
715 let observation = process.observe().expect("own process is alive");
716 let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
717 assert_eq!(observation.executable, Some(own_image));
718 assert_eq!(start_time(std::process::id()), Some(observation.start_time));
719 }
720
721 #[test]
722 fn child_start_time_is_stable_and_differs_from_ours() {
723 let mut child = spawn_sleep();
724 let pid = child.id();
725 let process = Process::open(pid).unwrap().unwrap();
726 let observation = wait_for_executable(&process, sleep_identity());
727 assert_eq!(observation.executable, Some(sleep_identity()));
728 assert_eq!(start_time(pid), Some(observation.start_time));
729 child.kill().unwrap();
730 child.wait().unwrap();
731 }
732
733 #[test]
734 fn a_signalled_and_unreaped_child_reads_as_exited() {
735 let mut child = spawn_sleep();
736 let process = Process::open(child.id()).unwrap().unwrap();
737 assert!(process.signal(Signal::Terminate).unwrap());
738 let deadline = Instant::now() + Duration::from_secs(5);
739 while process.observe().is_some() {
740 assert!(Instant::now() < deadline, "child still observed as alive");
741 std::thread::sleep(Duration::from_millis(10));
742 }
743 assert_eq!(start_time(child.id()), None);
745 child.wait().unwrap();
746 }
747
748 #[test]
749 fn a_reaped_child_cannot_be_opened_or_observed() {
750 let mut child = spawn_sleep();
751 let pid = child.id();
752 child.kill().unwrap();
753 child.wait().unwrap();
754 if let Some(process) = Process::open(pid).unwrap() {
756 if let Some(observation) = process.observe() {
757 assert_ne!(observation.executable, Some(sleep_identity()));
758 }
759 }
760 }
761
762 #[cfg(target_os = "macos")]
766 #[test]
767 fn macos_start_time_is_microseconds_since_the_epoch() {
768 let now = std::time::SystemTime::now()
769 .duration_since(std::time::UNIX_EPOCH)
770 .unwrap()
771 .as_micros() as u64;
772 let started = start_time(std::process::id()).unwrap();
773 assert!(started <= now, "start time {started} is after now {now}");
774 assert!(
775 now - started < 3_600 * 1_000_000,
776 "start time {started} is more than an hour before now {now}"
777 );
778 }
779
780 fn thread_cpu_time() -> Duration {
784 let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
785 Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
786 }
787
788 fn burn_cpu(cpu: Duration) {
794 let start = thread_cpu_time();
795 let give_up = Instant::now() + Duration::from_secs(60);
796 let mut value = 0u64;
797 while thread_cpu_time().saturating_sub(start) < cpu {
798 assert!(
799 Instant::now() < give_up,
800 "thread CPU clock stopped advancing"
801 );
802 for step in 0..10_000u64 {
803 value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
804 }
805 }
806 std::hint::black_box(value);
807 }
808
809 #[test]
810 fn own_resource_usage_is_present_and_plausible() {
811 let pages = vec![0xa5u8; 8 * 1024 * 1024];
816 std::hint::black_box(&pages);
817 let usage = resource_usage(std::process::id()).expect("own process is readable");
818 assert!(
819 usage.memory_bytes >= pages.len() as u64,
820 "memory {} bytes cannot account for {} touched private bytes",
821 usage.memory_bytes,
822 pages.len()
823 );
824 std::hint::black_box(&pages);
825 assert!(
826 usage.memory_bytes < 64 * 1024 * 1024 * 1024,
827 "memory {} bytes is implausibly large",
828 usage.memory_bytes
829 );
830 #[cfg(target_os = "macos")]
831 assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
832 #[cfg(target_os = "linux")]
833 {
834 assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
835 assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
836 }
837 }
838
839 #[test]
844 fn own_cpu_time_grows_by_about_the_busy_work_done() {
845 let pid = std::process::id();
846 let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
847 let before = total(resource_usage(pid).unwrap());
848 let busy = Duration::from_millis(400);
849 burn_cpu(busy);
850 let after = total(resource_usage(pid).unwrap());
851 let grown = after.saturating_sub(before);
852 assert!(
857 grown >= busy * 9 / 10,
858 "cpu time grew by {grown:?} over {busy:?} of busy work"
859 );
860 }
861
862 #[test]
863 fn a_child_reads_its_own_usage_not_ours() {
864 struct ChildGuard(Child);
865 impl Drop for ChildGuard {
866 fn drop(&mut self) {
867 let _ = self.0.kill();
868 let _ = self.0.wait();
869 }
870 }
871
872 let ours = resource_usage(std::process::id()).unwrap();
876 let bytes = usize::try_from(ours.memory_bytes)
877 .unwrap()
878 .checked_add(64 * 1024 * 1024)
879 .unwrap();
880 let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
881 let ready = scratch.join("ready");
882 let mut child = ChildGuard(
883 Command::new(std::env::current_exe().unwrap())
884 .args([
885 "tests::resource_usage_child",
886 "--exact",
887 "--ignored",
888 "--nocapture",
889 "--test-threads=1",
890 ])
891 .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
892 .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
893 .stdin(Stdio::piped())
894 .stdout(Stdio::null())
895 .spawn()
896 .unwrap(),
897 );
898 let deadline = Instant::now() + Duration::from_secs(10);
899 while !ready.exists() {
900 assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
901 assert!(Instant::now() < deadline, "memory child never became ready");
902 std::thread::sleep(Duration::from_millis(5));
903 }
904
905 let ours = resource_usage(std::process::id()).unwrap();
906 let usage = resource_usage(child.0.id()).expect("live child is readable");
907 assert!(
910 ours.memory_bytes < bytes as u64,
911 "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
912 ours.memory_bytes,
913 );
914 assert!(
915 usage.memory_bytes >= bytes as u64,
916 "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
917 usage.memory_bytes,
918 ours.memory_bytes,
919 );
920 }
921
922 #[test]
923 #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
924 fn resource_usage_child() {
925 let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
926 .unwrap()
927 .parse()
928 .unwrap();
929 let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
930 let pages = vec![0xa5u8; bytes];
931 std::hint::black_box(&pages);
932 std::fs::write(ready, b"ready").unwrap();
933 let _ = std::io::stdin().read(&mut [0]);
934 std::hint::black_box(&pages);
935 }
936
937 #[test]
938 fn an_exited_child_reads_as_unavailable_not_zero() {
939 let mut child = spawn_sleep();
940 let pid = child.id();
941 child.kill().unwrap();
942 let deadline = Instant::now() + Duration::from_secs(5);
944 while start_time(pid).is_some() {
945 assert!(Instant::now() < deadline, "child still observed as alive");
946 std::thread::sleep(Duration::from_millis(10));
947 }
948 assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
949 child.wait().unwrap();
950 if let Some(usage) = resource_usage(pid) {
953 assert!(usage.memory_bytes > 0, "a reused pid is some live process");
954 }
955 }
956
957 #[test]
958 fn a_pid_with_no_process_reads_as_unavailable() {
959 assert_eq!(resource_usage(i32::MAX as u32), None);
962 assert_eq!(resource_usage(u32::MAX), None);
964 }
965
966 #[cfg(target_os = "linux")]
967 #[test]
968 fn linux_signals_go_through_a_pidfd() {
969 let mut child = spawn_sleep();
970 let process = Process::open(child.id()).unwrap().unwrap();
971 assert!(process.signals_through_pidfd());
972 child.kill().unwrap();
973 child.wait().unwrap();
974 assert!(!process.signal(Signal::Kill).unwrap());
976 }
977}