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, move_file_aside_nofollow_at, move_file_to_noreplace_at,
109 open_directory_nofollow_at, open_or_create_private_directory_at,
110 open_single_link_file_nofollow_at, probe_retained_directory_write,
111 probe_retained_regular_file_at, retained_directory_path, retained_regular_file_at,
112 OpenRetainedError, RetainedMovedFile, RetainedTempFile,
113};
114#[cfg(all(unix, feature = "test-support"))]
115pub mod fork_exec_test;
116pub mod host;
117pub mod launch_nonce;
118pub mod local_peer;
119#[cfg(windows)]
120mod loopback_connect;
121#[cfg(windows)]
122pub use loopback_connect::connect_loopback;
123pub mod named_pipe;
124pub mod privacy_identity;
125mod private_directory;
126#[cfg(unix)]
127pub mod process_group;
128pub mod process_identity;
129pub use private_directory::create_private_directory_exclusive;
130pub mod registration_channel;
131pub mod script_pipe;
132pub mod socket_peer;
133#[cfg(windows)]
134pub mod user_path;
135#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
136pub mod windows_acl;
137#[cfg(unix)]
138pub use launch_nonce::LaunchNonceHandoff;
139pub use launch_nonce::{
140 launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
141 LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
142};
143
144#[cfg(windows)]
145pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
146
147pub use registration_channel::{
148 registration_refusal, supervised, take_registration_channel, RegistrationChannel,
149 RegistrationChannelError, RegistrationRefusal,
150};
151
152#[cfg(target_os = "linux")]
153mod linux;
154#[cfg(target_os = "macos")]
155mod macos;
156
157#[cfg(target_os = "macos")]
158pub use macos::owned_child_start_time;
159#[cfg(windows)]
160mod windows;
161#[cfg(all(test, windows))]
162mod windows_tests;
163#[cfg(windows)]
164pub use windows::{
165 ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
166};
167
168#[cfg(target_os = "linux")]
169use linux as platform;
170#[cfg(target_os = "macos")]
171use macos as platform;
172
173use std::{io, path::Path};
174
175pub const PROCESS_IDENTITY_SUPPORTED: bool =
177 cfg!(any(target_os = "linux", target_os = "macos", windows));
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
182pub struct FileIdentity {
183 pub device: u64,
184 pub inode: u64,
185}
186
187pub fn file_identity(path: &Path) -> Option<FileIdentity> {
190 #[cfg(unix)]
191 {
192 use std::os::unix::fs::MetadataExt;
193
194 std::fs::metadata(path).ok().map(|metadata| FileIdentity {
195 device: metadata.dev(),
196 inode: metadata.ino(),
197 })
198 }
199 #[cfg(not(unix))]
200 {
201 let _ = path;
202 None
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub struct Observation {
209 pub start_time: u64,
214 pub executable: Option<FileIdentity>,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum ExecutableAccess {
226 Readable,
227 PermissionDenied,
228 Unavailable,
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum Signal {
234 Terminate,
236 Kill,
238}
239
240pub fn start_time(pid: u32) -> Option<u64> {
244 #[cfg(any(target_os = "linux", target_os = "macos"))]
245 {
246 platform::start_time(pid)
247 }
248 #[cfg(windows)]
249 {
250 Process::open(pid)
251 .ok()??
252 .observe()
253 .map(|observation| observation.start_time)
254 }
255 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
256 {
257 let _ = pid;
258 None
259 }
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub(crate) enum IdentityRead {
265 Alive(u64),
266 #[cfg_attr(windows, allow(dead_code))]
267 Gone,
269 Unknown,
270}
271
272#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
273mod identity_read_tests {
274 use super::*;
275
276 #[test]
277 fn identity_probe_distinguishes_alive_gone_and_invalid() {
278 let mut child = std::process::Command::new("/bin/sh")
279 .args(["-c", "exit 0"])
280 .spawn()
281 .unwrap();
282 let pid = child.id();
283 let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
284 while read_identity(pid) != IdentityRead::Gone {
285 assert!(
286 std::time::Instant::now() < until,
287 "an exited owned child must become gone before reaping"
288 );
289 std::thread::yield_now();
290 }
291 child.wait().unwrap();
292 assert_eq!(
293 read_identity(pid),
294 IdentityRead::Gone,
295 "a missing owned PID is gone"
296 );
297 assert_eq!(read_identity(0), IdentityRead::Unknown);
298 assert!(matches!(
299 read_identity(std::process::id()),
300 IdentityRead::Alive(_)
301 ));
302 }
303}
304
305#[cfg(not(windows))]
306fn read_identity(pid: u32) -> IdentityRead {
307 #[cfg(any(target_os = "linux", target_os = "macos"))]
308 {
309 platform::read_identity(pid)
310 }
311 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
312 {
313 start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
314 }
315}
316
317mod process_tree;
318pub use process_tree::{BirthBaseline, ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
319
320pub fn process_start_time_ms(pid: u32) -> Option<u64> {
328 start_time_ms_from_native(start_time(pid)?)
329}
330
331fn start_time_ms_from_native(raw: u64) -> Option<u64> {
332 #[cfg(target_os = "linux")]
333 {
334 linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
335 }
336 #[cfg(target_os = "macos")]
337 {
338 Some(raw / 1_000)
339 }
340 #[cfg(windows)]
341 {
342 (raw / 10_000).checked_sub(11_644_473_600_000)
343 }
344 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
345 {
346 let _ = raw;
347 None
348 }
349}
350
351#[cfg(target_os = "linux")]
352fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
353 let boot = read_boot()?
357 .lines()
358 .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
359 boot.checked_mul(1_000)?
360 .checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
361}
362
363#[cfg(all(test, target_os = "linux"))]
364#[test]
365fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
366 let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
367 let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
368 assert_eq!(after - before, 2_000);
369}
370
371pub fn process_start_time_precision_ms() -> u64 {
373 #[cfg(target_os = "linux")]
374 {
375 1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
376 }
377 #[cfg(not(target_os = "linux"))]
378 {
379 1
380 }
381}
382
383pub fn parent_pid(pid: u32) -> Option<u32> {
386 #[cfg(any(target_os = "linux", target_os = "macos"))]
387 {
388 platform::parent_pid(pid)
389 }
390 #[cfg(windows)]
391 {
392 windows::parent_pid(pid)
393 }
394 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
395 {
396 let _ = pid;
397 None
398 }
399}
400
401pub const RESOURCE_USAGE_SUPPORTED: bool =
405 cfg!(any(target_os = "linux", target_os = "macos", windows));
406
407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410pub enum MemoryKind {
411 PhysFootprint,
415 ResidentSet,
419 WindowsWorkingSet,
422}
423
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub struct ResourceUsage {
430 pub memory_bytes: u64,
432 pub memory_kind: MemoryKind,
433 pub swap_bytes: Option<u64>,
436 pub cpu_user: std::time::Duration,
438 pub cpu_system: std::time::Duration,
440}
441
442pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
454 #[cfg(any(target_os = "linux", target_os = "macos"))]
455 {
456 platform::resource_usage(pid)
457 }
458 #[cfg(windows)]
459 {
460 Process::open(pid).ok()??.resource_usage()
461 }
462 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
463 {
464 let _ = pid;
465 None
466 }
467}
468
469#[derive(Debug)]
471pub struct Process {
472 pid: u32,
473 #[cfg(target_os = "linux")]
474 pidfd: Option<std::os::fd::OwnedFd>,
475 #[cfg(windows)]
476 handle: std::os::windows::io::OwnedHandle,
477}
478
479impl Process {
480 pub fn open(pid: u32) -> io::Result<Option<Self>> {
490 #[cfg(target_os = "linux")]
491 {
492 linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
493 }
494 #[cfg(target_os = "macos")]
495 {
496 Ok(platform::exists(pid).then_some(Self { pid }))
497 }
498 #[cfg(windows)]
499 {
500 windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
501 }
502 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
503 {
504 let _ = pid;
505 Err(io::Error::new(
506 io::ErrorKind::Unsupported,
507 "process identity is not available on this platform",
508 ))
509 }
510 }
511
512 pub fn pid(&self) -> u32 {
513 self.pid
514 }
515
516 pub fn signals_through_pidfd(&self) -> bool {
519 #[cfg(target_os = "linux")]
520 {
521 self.pidfd.is_some()
522 }
523 #[cfg(not(target_os = "linux"))]
524 {
525 false
526 }
527 }
528
529 pub fn observe(&self) -> Option<Observation> {
533 self.observe_with_executable_access()
534 .map(|(observed, _)| observed)
535 }
536
537 pub fn is_alive_but_unobservable(&self) -> bool {
541 #[cfg(target_os = "linux")]
542 {
543 linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
544 }
545 #[cfg(not(target_os = "linux"))]
546 {
547 false
548 }
549 }
550
551 pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
555 #[cfg(any(target_os = "linux", target_os = "macos"))]
556 {
557 #[cfg(target_os = "linux")]
558 if !linux::pidfd_alive(self.pidfd.as_ref()) {
559 return None;
560 }
561 let start_time = platform::start_time(self.pid)?;
562 #[cfg(target_os = "linux")]
563 let (executable, access) = match linux::executable_identity(self.pid) {
564 Ok(identity) => (Some(identity), ExecutableAccess::Readable),
565 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
566 (None, ExecutableAccess::PermissionDenied)
567 }
568 Err(_) => (None, ExecutableAccess::Unavailable),
569 };
570 #[cfg(target_os = "macos")]
571 let executable = macos::executable_identity(self.pid);
572 #[cfg(target_os = "macos")]
573 let access = if executable.is_some() {
574 ExecutableAccess::Readable
575 } else {
576 ExecutableAccess::Unavailable
577 };
578 Some((
579 Observation {
580 start_time,
581 executable,
582 },
583 access,
584 ))
585 }
586 #[cfg(windows)]
587 {
588 windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
589 }
590 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
591 {
592 None
593 }
594 }
595
596 #[cfg(windows)]
599 pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
600 windows::wait(self, timeout)
601 }
602
603 #[cfg(windows)]
607 pub fn force_stop(
608 &self,
609 expected_start_time: u64,
610 timeout: std::time::Duration,
611 ) -> io::Result<bool> {
612 windows::force_stop(self, expected_start_time, timeout)
613 }
614
615 #[cfg(windows)]
620 pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
621 windows::terminate_with_exit_code(self, exit_code)
622 }
623
624 #[cfg(windows)]
626 pub fn resource_usage(&self) -> Option<ResourceUsage> {
627 windows::resource_usage(self)
628 }
629
630 #[cfg(windows)]
633 pub fn cumulative_cpu_ms(&self) -> Option<u64> {
634 windows::cumulative_cpu_ms(self)
635 }
636
637 pub fn signal(&self, signal: Signal) -> io::Result<bool> {
651 #[cfg(any(target_os = "linux", target_os = "macos"))]
652 {
653 #[cfg(target_os = "linux")]
654 let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
655 #[cfg(target_os = "macos")]
656 let result = macos::signal(self.pid, signal);
657 match result {
658 Ok(()) => Ok(true),
659 Err(rustix::io::Errno::SRCH) => Ok(false),
660 Err(error) => Err(error.into()),
661 }
662 }
663 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
664 {
665 let _ = signal;
666 Err(io::Error::new(
667 io::ErrorKind::Unsupported,
668 "process signalling is not available on this platform",
669 ))
670 }
671 }
672}
673
674#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
675mod tests {
676 use std::{
677 io::Read,
678 process::{Child, Command, Stdio},
679 time::{Duration, Instant},
680 };
681
682 use super::*;
683
684 fn spawn_sleep() -> Child {
685 Command::new("sleep")
686 .arg("60")
687 .spawn()
688 .expect("spawn sleep")
689 }
690
691 fn sleep_identity() -> FileIdentity {
693 let path = ["/bin/sleep", "/usr/bin/sleep"]
694 .into_iter()
695 .find(|path| Path::new(path).exists())
696 .expect("sleep is installed");
697 file_identity(Path::new(path)).expect("stat sleep")
698 }
699
700 fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
703 let deadline = Instant::now() + Duration::from_secs(5);
704 loop {
705 let observation = process.observe().expect("child is alive");
706 if observation.executable == Some(expected) || Instant::now() > deadline {
707 return observation;
708 }
709 std::thread::sleep(Duration::from_millis(10));
710 }
711 }
712
713 #[test]
714 fn own_process_is_observable_with_its_own_image() {
715 let process = Process::open(std::process::id())
716 .expect("open own process")
717 .expect("own process exists");
718 let observation = process.observe().expect("own process is alive");
719 let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
720 assert_eq!(observation.executable, Some(own_image));
721 assert_eq!(start_time(std::process::id()), Some(observation.start_time));
722 }
723
724 #[test]
725 fn child_start_time_is_stable_and_differs_from_ours() {
726 let mut child = spawn_sleep();
727 let pid = child.id();
728 let process = Process::open(pid).unwrap().unwrap();
729 let observation = wait_for_executable(&process, sleep_identity());
730 assert_eq!(observation.executable, Some(sleep_identity()));
731 assert_eq!(start_time(pid), Some(observation.start_time));
732 child.kill().unwrap();
733 child.wait().unwrap();
734 }
735
736 #[test]
737 fn a_signalled_and_unreaped_child_reads_as_exited() {
738 let mut child = spawn_sleep();
739 let process = Process::open(child.id()).unwrap().unwrap();
740 assert!(process.signal(Signal::Terminate).unwrap());
741 let deadline = Instant::now() + Duration::from_secs(5);
742 while process.observe().is_some() {
743 assert!(Instant::now() < deadline, "child still observed as alive");
744 std::thread::sleep(Duration::from_millis(10));
745 }
746 assert_eq!(start_time(child.id()), None);
748 child.wait().unwrap();
749 }
750
751 #[test]
752 fn a_reaped_child_cannot_be_opened_or_observed() {
753 let mut child = spawn_sleep();
754 let pid = child.id();
755 child.kill().unwrap();
756 child.wait().unwrap();
757 if let Some(process) = Process::open(pid).unwrap() {
759 if let Some(observation) = process.observe() {
760 assert_ne!(observation.executable, Some(sleep_identity()));
761 }
762 }
763 }
764
765 #[cfg(target_os = "macos")]
769 #[test]
770 fn macos_start_time_is_microseconds_since_the_epoch() {
771 let now = std::time::SystemTime::now()
772 .duration_since(std::time::UNIX_EPOCH)
773 .unwrap()
774 .as_micros() as u64;
775 let started = start_time(std::process::id()).unwrap();
776 assert!(started <= now, "start time {started} is after now {now}");
777 assert!(
778 now - started < 3_600 * 1_000_000,
779 "start time {started} is more than an hour before now {now}"
780 );
781 }
782
783 fn thread_cpu_time() -> Duration {
787 let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
788 Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
789 }
790
791 fn burn_cpu(cpu: Duration) {
797 let start = thread_cpu_time();
798 let give_up = Instant::now() + Duration::from_secs(60);
799 let mut value = 0u64;
800 while thread_cpu_time().saturating_sub(start) < cpu {
801 assert!(
802 Instant::now() < give_up,
803 "thread CPU clock stopped advancing"
804 );
805 for step in 0..10_000u64 {
806 value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
807 }
808 }
809 std::hint::black_box(value);
810 }
811
812 #[test]
813 fn own_resource_usage_is_present_and_plausible() {
814 let pages = vec![0xa5u8; 8 * 1024 * 1024];
819 std::hint::black_box(&pages);
820 let usage = resource_usage(std::process::id()).expect("own process is readable");
821 assert!(
822 usage.memory_bytes >= pages.len() as u64,
823 "memory {} bytes cannot account for {} touched private bytes",
824 usage.memory_bytes,
825 pages.len()
826 );
827 std::hint::black_box(&pages);
828 assert!(
829 usage.memory_bytes < 64 * 1024 * 1024 * 1024,
830 "memory {} bytes is implausibly large",
831 usage.memory_bytes
832 );
833 #[cfg(target_os = "macos")]
834 assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
835 #[cfg(target_os = "linux")]
836 {
837 assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
838 assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
839 }
840 }
841
842 #[test]
847 fn own_cpu_time_grows_by_about_the_busy_work_done() {
848 let pid = std::process::id();
849 let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
850 let before = total(resource_usage(pid).unwrap());
851 let busy = Duration::from_millis(400);
852 burn_cpu(busy);
853 let after = total(resource_usage(pid).unwrap());
854 let grown = after.saturating_sub(before);
855 assert!(
860 grown >= busy * 9 / 10,
861 "cpu time grew by {grown:?} over {busy:?} of busy work"
862 );
863 }
864
865 #[test]
866 fn a_child_reads_its_own_usage_not_ours() {
867 struct ChildGuard(Child);
868 impl Drop for ChildGuard {
869 fn drop(&mut self) {
870 let _ = self.0.kill();
871 let _ = self.0.wait();
872 }
873 }
874
875 let ours = resource_usage(std::process::id()).unwrap();
879 let bytes = usize::try_from(ours.memory_bytes)
880 .unwrap()
881 .checked_add(64 * 1024 * 1024)
882 .unwrap();
883 let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
884 let ready = scratch.join("ready");
885 let mut child = ChildGuard(
886 Command::new(std::env::current_exe().unwrap())
887 .args([
888 "tests::resource_usage_child",
889 "--exact",
890 "--ignored",
891 "--nocapture",
892 "--test-threads=1",
893 ])
894 .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
895 .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
896 .stdin(Stdio::piped())
897 .stdout(Stdio::null())
898 .spawn()
899 .unwrap(),
900 );
901 let deadline = Instant::now() + Duration::from_secs(10);
902 while !ready.exists() {
903 assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
904 assert!(Instant::now() < deadline, "memory child never became ready");
905 std::thread::sleep(Duration::from_millis(5));
906 }
907
908 let ours = resource_usage(std::process::id()).unwrap();
909 let usage = resource_usage(child.0.id()).expect("live child is readable");
910 assert!(
913 ours.memory_bytes < bytes as u64,
914 "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
915 ours.memory_bytes,
916 );
917 assert!(
918 usage.memory_bytes >= bytes as u64,
919 "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
920 usage.memory_bytes,
921 ours.memory_bytes,
922 );
923 }
924
925 #[test]
926 #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
927 fn resource_usage_child() {
928 let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
929 .unwrap()
930 .parse()
931 .unwrap();
932 let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
933 let pages = vec![0xa5u8; bytes];
934 std::hint::black_box(&pages);
935 std::fs::write(ready, b"ready").unwrap();
936 let _ = std::io::stdin().read(&mut [0]);
937 std::hint::black_box(&pages);
938 }
939
940 #[test]
941 fn an_exited_child_reads_as_unavailable_not_zero() {
942 let mut child = spawn_sleep();
943 let pid = child.id();
944 child.kill().unwrap();
945 let deadline = Instant::now() + Duration::from_secs(5);
947 while start_time(pid).is_some() {
948 assert!(Instant::now() < deadline, "child still observed as alive");
949 std::thread::sleep(Duration::from_millis(10));
950 }
951 assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
952 child.wait().unwrap();
953 if let Some(usage) = resource_usage(pid) {
956 assert!(usage.memory_bytes > 0, "a reused pid is some live process");
957 }
958 }
959
960 #[test]
961 fn a_pid_with_no_process_reads_as_unavailable() {
962 assert_eq!(resource_usage(i32::MAX as u32), None);
965 assert_eq!(resource_usage(u32::MAX), None);
967 }
968
969 #[cfg(target_os = "linux")]
970 #[test]
971 fn linux_signals_go_through_a_pidfd() {
972 let mut child = spawn_sleep();
973 let process = Process::open(child.id()).unwrap().unwrap();
974 assert!(process.signals_through_pidfd());
975 child.kill().unwrap();
976 child.wait().unwrap();
977 assert!(!process.signal(Signal::Kill).unwrap());
979 }
980}