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