Debian Codegraph @

tests/waitpid_tests.rs

raw symbols SCIP
1 //! Comprehensive `waitpid()` tests
2 //!
3 //! This module tests all aspects of the `waitpid()` function including:
4 //! - Error handling (ECHILD for invalid/already-waited PIDs)
5 //! - Exit status codes (various exit codes)
6 //! - Signal termination (WIFSIGNALED)
7 //! - Status code inspection (WIFEXITED, WEXITSTATUS, WTERMSIG)
8 //! - Double-wait scenarios
9 //!
10 //! These tests ensure waitpid correctly handles both success and error cases.
11
12 #![allow(clippy::expect_used)]
13 #![allow(clippy::unwrap_used)]
14 #![allow(clippy::panic)]
15 #![allow(clippy::match_wild_err_arm)]
16 #![allow(clippy::similar_names)]
17 #![allow(clippy::uninlined_format_args)]
18 #![allow(clippy::indexing_slicing)]
19
20 use fork::{Fork, fork, waitpid, waitpid_nohang};
21 use libc::{WEXITSTATUS, WIFEXITED, WIFSIGNALED, WTERMSIG};
22 use std::{
23 process::exit,
24 sync::atomic::{AtomicBool, Ordering},
25 thread,
26 time::Duration,
27 };
28
29 #[test]
30 fn test_waitpid_invalid_pid() {
31 // Tests that waitpid returns error for non-existent PID
32 // Expected behavior:
33 // 1. Try to wait on a PID that doesn't exist
34 // 2. waitpid should fail with ECHILD error
35 // 3. Verifies error handling for invalid PIDs
36 match fork() {
37 Ok(Fork::Parent(_)) => {
38 // Try to wait on non-existent PID (very high number unlikely to exist)
39 let result = waitpid(999_999);
40 assert!(result.is_err(), "waitpid on invalid PID should fail");
41
42 // Should be ECHILD (no child process)
43 let err = result.unwrap_err();
44 assert_eq!(
45 err.raw_os_error(),
46 Some(libc::ECHILD),
47 "Should return ECHILD for non-existent child"
48 );
49 }
50 Ok(Fork::Child) => exit(0),
51 Err(_) => panic!("Fork failed"),
52 }
53 }
54
55 #[test]
56 fn test_waitpid_double_wait() {
57 // Tests that waitpid fails when called twice on same child
58 // Expected behavior:
59 // 1. First waitpid succeeds and reaps the child
60 // 2. Second waitpid on same PID fails with ECHILD
61 // 3. Demonstrates that child can only be waited once
62 match fork() {
63 Ok(Fork::Parent(child)) => {
64 // First wait succeeds
65 let result = waitpid(child);
66 assert!(result.is_ok(), "First waitpid should succeed");
67
68 // Give child time to fully exit
69 std::thread::sleep(std::time::Duration::from_millis(10));
70
71 // Second wait should fail with ECHILD (child already reaped)
72 let result = waitpid(child);
73 assert!(result.is_err(), "Second waitpid should fail");
74 assert_eq!(
75 result.unwrap_err().raw_os_error(),
76 Some(libc::ECHILD),
77 "Should return ECHILD for already-waited child"
78 );
79 }
80 Ok(Fork::Child) => exit(0),
81 Err(_) => panic!("Fork failed"),
82 }
83 }
84
85 #[test]
86 fn test_waitpid_exit_code_zero() {
87 // Tests that waitpid correctly reports exit code 0 (success)
88 // Expected behavior:
89 // 1. Child exits with code 0
90 // 2. Parent calls waitpid and gets status
91 // 3. WIFEXITED(status) is true
92 // 4. WEXITSTATUS(status) returns 0
93 match fork() {
94 Ok(Fork::Parent(child)) => {
95 let status = waitpid(child).expect("waitpid failed");
96 assert!(WIFEXITED(status), "Child should have exited normally");
97 assert_eq!(WEXITSTATUS(status), 0, "Exit code should be 0");
98 }
99 Ok(Fork::Child) => exit(0),
100 Err(_) => panic!("Fork failed"),
101 }
102 }
103
104 #[test]
105 fn test_waitpid_exit_code_one() {
106 // Tests that waitpid correctly reports exit code 1 (error)
107 match fork() {
108 Ok(Fork::Parent(child)) => {
109 let status = waitpid(child).expect("waitpid failed");
110 assert!(WIFEXITED(status), "Child should have exited normally");
111 assert_eq!(WEXITSTATUS(status), 1, "Exit code should be 1");
112 }
113 Ok(Fork::Child) => exit(1),
114 Err(_) => panic!("Fork failed"),
115 }
116 }
117
118 #[test]
119 fn test_waitpid_exit_code_42() {
120 // Tests that waitpid correctly reports arbitrary exit code 42
121 match fork() {
122 Ok(Fork::Parent(child)) => {
123 let status = waitpid(child).expect("waitpid failed");
124 assert!(WIFEXITED(status), "Child should have exited normally");
125 assert_eq!(WEXITSTATUS(status), 42, "Exit code should be 42");
126 }
127 Ok(Fork::Child) => exit(42),
128 Err(_) => panic!("Fork failed"),
129 }
130 }
131
132 #[test]
133 fn test_waitpid_exit_code_127() {
134 // Tests that waitpid correctly reports exit code 127
135 // (commonly used for "command not found")
136 match fork() {
137 Ok(Fork::Parent(child)) => {
138 let status = waitpid(child).expect("waitpid failed");
139 assert!(WIFEXITED(status), "Child should have exited normally");
140 assert_eq!(WEXITSTATUS(status), 127, "Exit code should be 127");
141 }
142 Ok(Fork::Child) => exit(127),
143 Err(_) => panic!("Fork failed"),
144 }
145 }
146
147 #[test]
148 fn test_waitpid_multiple_exit_codes() {
149 // Tests that waitpid correctly reports various exit codes
150 // Tests multiple children with different exit codes sequentially
151 for exit_code in [0, 1, 2, 42, 100, 127, 255] {
152 match fork() {
153 Ok(Fork::Parent(child)) => {
154 let status = waitpid(child).expect("waitpid failed");
155 assert!(WIFEXITED(status), "Child should have exited normally");
156 assert_eq!(
157 WEXITSTATUS(status),
158 exit_code,
159 "Exit code should be {}",
160 exit_code
161 );
162 }
163 Ok(Fork::Child) => exit(exit_code),
164 Err(_) => panic!("Fork failed for exit code {}", exit_code),
165 }
166 }
167 }
168
169 #[test]
170 fn test_waitpid_signal_termination_sigkill() {
171 // Tests that waitpid correctly reports signal termination
172 // Expected behavior:
173 // 1. Child kills itself with SIGKILL
174 // 2. waitpid succeeds and returns status
175 // 3. WIFSIGNALED(status) is true
176 // 4. WTERMSIG(status) returns SIGKILL
177 match fork() {
178 Ok(Fork::Parent(child)) => {
179 let status = waitpid(child).expect("waitpid failed");
180 assert!(
181 WIFSIGNALED(status),
182 "Child should have been terminated by signal"
183 );
184 assert_eq!(WTERMSIG(status), libc::SIGKILL, "Signal should be SIGKILL");
185 }
186 Ok(Fork::Child) => {
187 // Kill ourselves with SIGKILL
188 unsafe {
189 libc::kill(libc::getpid(), libc::SIGKILL);
190 }
191 // Never reached
192 exit(0);
193 }
194 Err(_) => panic!("Fork failed"),
195 }
196 }
197
198 #[test]
199 fn test_waitpid_signal_termination_sigterm() {
200 // Tests that waitpid correctly reports SIGTERM termination
201 match fork() {
202 Ok(Fork::Parent(child)) => {
203 let status = waitpid(child).expect("waitpid failed");
204 assert!(
205 WIFSIGNALED(status),
206 "Child should have been terminated by signal"
207 );
208 assert_eq!(WTERMSIG(status), libc::SIGTERM, "Signal should be SIGTERM");
209 }
210 Ok(Fork::Child) => {
211 // Kill ourselves with SIGTERM
212 unsafe {
213 libc::kill(libc::getpid(), libc::SIGTERM);
214 }
215 // Never reached
216 exit(0);
217 }
218 Err(_) => panic!("Fork failed"),
219 }
220 }
221
222 #[test]
223 fn test_waitpid_signal_termination_sigabrt() {
224 // Tests that waitpid correctly reports SIGABRT termination (abort)
225 match fork() {
226 Ok(Fork::Parent(child)) => {
227 let status = waitpid(child).expect("waitpid failed");
228 assert!(
229 WIFSIGNALED(status),
230 "Child should have been terminated by signal"
231 );
232 assert_eq!(WTERMSIG(status), libc::SIGABRT, "Signal should be SIGABRT");
233 }
234 Ok(Fork::Child) => {
235 // Abort
236 unsafe {
237 libc::abort();
238 }
239 // Never reached
240 }
241 Err(_) => panic!("Fork failed"),
242 }
243 }
244
245 #[test]
246 fn test_waitpid_distinguishes_exit_vs_signal() {
247 // Tests that waitpid can distinguish between normal exit and signal termination
248 // Expected behavior:
249 // 1. First child exits normally with code 9
250 // 2. Second child is killed with signal 9 (SIGKILL)
251 // 3. waitpid should correctly identify each case
252
253 // Normal exit with code 9
254 match fork() {
255 Ok(Fork::Parent(child)) => {
256 let status = waitpid(child).expect("waitpid failed");
257 assert!(WIFEXITED(status), "First child should have exited normally");
258 assert!(!WIFSIGNALED(status), "First child should not be signaled");
259 assert_eq!(WEXITSTATUS(status), 9, "Exit code should be 9");
260 }
261 Ok(Fork::Child) => exit(9),
262 Err(_) => panic!("Fork failed"),
263 }
264
265 // Signal termination with signal 9 (SIGKILL)
266 match fork() {
267 Ok(Fork::Parent(child)) => {
268 let status = waitpid(child).expect("waitpid failed");
269 assert!(WIFSIGNALED(status), "Second child should be signaled");
270 assert!(
271 !WIFEXITED(status),
272 "Second child should not have exited normally"
273 );
274 assert_eq!(
275 WTERMSIG(status),
276 libc::SIGKILL,
277 "Signal should be SIGKILL (9)"
278 );
279 }
280 Ok(Fork::Child) => {
281 unsafe {
282 libc::kill(libc::getpid(), libc::SIGKILL);
283 }
284 exit(0);
285 }
286 Err(_) => panic!("Fork failed"),
287 }
288 }
289
290 #[test]
291 fn test_waitpid_returns_raw_status() {
292 // Tests that waitpid returns the raw status code that can be inspected
293 // Expected behavior:
294 // 1. waitpid returns io::Result<c_int> (raw status)
295 // 2. Status can be examined with WIFEXITED, WEXITSTATUS, etc.
296 // 3. Verifies the function signature change from v0.5.0
297 match fork() {
298 Ok(Fork::Parent(child)) => {
299 let status: libc::c_int = waitpid(child).expect("waitpid failed");
300
301 // Verify we can use the raw status with libc macros
302 assert!(WIFEXITED(status));
303 let exit_code = WEXITSTATUS(status);
304 assert_eq!(exit_code, 123);
305 }
306 Ok(Fork::Child) => exit(123),
307 Err(_) => panic!("Fork failed"),
308 }
309 }
310
311 #[test]
312 fn test_waitpid_retries_on_eintr() {
313 extern "C" fn handle_sigusr1(_sig: libc::c_int) {
314 SIGNAL_RECEIVED.store(true, Ordering::SeqCst);
315 }
316
317 static SIGNAL_RECEIVED: AtomicBool = AtomicBool::new(false);
318
319 // Reset between potential re-runs
320 SIGNAL_RECEIVED.store(false, Ordering::SeqCst);
321
322 // Install a minimal handler so SIGUSR1 interrupts waitpid
323 // Use sigaction() instead of deprecated signal() for portability
324 unsafe {
325 let mut sa: libc::sigaction = std::mem::zeroed();
326
327 // Set the handler function (cast via pointer to satisfy clippy lint)
328 sa.sa_sigaction = handle_sigusr1 as *const () as usize;
329
330 // SA_RESTART would make interrupted syscalls restart automatically,
331 // but we want to test EINTR handling, so we don't set it
332 sa.sa_flags = 0;
333
334 // Install the signal handler
335 assert!(
336 libc::sigaction(libc::SIGUSR1, &raw const sa, std::ptr::null_mut()) != -1,
337 "Failed to install signal handler"
338 );
339 }
340
341 match fork() {
342 Ok(Fork::Parent(child)) => {
343 let parent_pid = unsafe { libc::getpid() };
344 let signal_thread = thread::spawn(move || {
345 thread::sleep(Duration::from_millis(10));
346 unsafe {
347 libc::kill(parent_pid, libc::SIGUSR1);
348 }
349 });
350
351 let status = waitpid(child).expect("waitpid failed after EINTR");
352 assert!(WIFEXITED(status));
353
354 signal_thread
355 .join()
356 .expect("signal thread should not panic");
357 assert!(
358 SIGNAL_RECEIVED.load(Ordering::SeqCst),
359 "Signal handler should have run"
360 );
361 }
362 Ok(Fork::Child) => {
363 // Sleep long enough for parent to block and be interrupted
364 std::thread::sleep(Duration::from_millis(50));
365 exit(0);
366 }
367 Err(_) => panic!("Fork failed"),
368 }
369 }
370
371 // ============================================================================
372 // waitpid_nohang() tests
373 // ============================================================================
374
375 #[test]
376 fn test_waitpid_nohang_child_still_running() {
377 // Tests that waitpid_nohang returns None when child is still running
378 // Expected behavior:
379 // 1. Child sleeps for a while
380 // 2. Parent checks immediately with waitpid_nohang
381 // 3. Should return Ok(None) because child hasn't exited yet
382 match fork() {
383 Ok(Fork::Parent(child)) => {
384 // Check immediately - child should still be running
385 match waitpid_nohang(child) {
386 Ok(None) => {
387 // Expected: child still running
388 }
389 Ok(Some(status)) => {
390 panic!("Child exited too quickly with status: {}", status);
391 }
392 Err(e) => {
393 panic!("waitpid_nohang failed: {}", e);
394 }
395 }
396
397 // Now wait for child to finish
398 let status = waitpid(child).expect("waitpid failed");
399 assert!(WIFEXITED(status));
400 }
401 Ok(Fork::Child) => {
402 // Child sleeps to ensure parent's check happens while we're running
403 std::thread::sleep(Duration::from_millis(100));
404 exit(0);
405 }
406 Err(_) => panic!("Fork failed"),
407 }
408 }
409
410 #[test]
411 fn test_waitpid_nohang_child_exited() {
412 // Tests that waitpid_nohang returns Some(status) when child has exited
413 // Expected behavior:
414 // 1. Child exits immediately
415 // 2. Parent waits a bit to ensure child exits
416 // 3. waitpid_nohang should return Ok(Some(status))
417 match fork() {
418 Ok(Fork::Parent(child)) => {
419 // Give child time to exit
420 std::thread::sleep(Duration::from_millis(50));
421
422 // Check if child exited
423 match waitpid_nohang(child) {
424 Ok(Some(status)) => {
425 assert!(WIFEXITED(status), "Child should have exited normally");
426 assert_eq!(WEXITSTATUS(status), 42);
427 }
428 Ok(None) => {
429 panic!("Child should have exited by now");
430 }
431 Err(e) => {
432 panic!("waitpid_nohang failed: {}", e);
433 }
434 }
435 }
436 Ok(Fork::Child) => {
437 // Child exits immediately
438 exit(42);
439 }
440 Err(_) => panic!("Fork failed"),
441 }
442 }
443
444 #[test]
445 fn test_waitpid_nohang_poll_until_exit() {
446 // Tests polling pattern with waitpid_nohang
447 // Expected behavior:
448 // 1. Parent polls child status in a loop
449 // 2. Returns None while child is running
450 // 3. Eventually returns Some(status) when child exits
451 match fork() {
452 Ok(Fork::Parent(child)) => {
453 let mut iterations = 0;
454 let mut child_exited = false;
455
456 // Poll for child exit
457 for _ in 0..20 {
458 iterations += 1;
459
460 match waitpid_nohang(child) {
461 Ok(Some(status)) => {
462 assert!(WIFEXITED(status));
463 assert_eq!(WEXITSTATUS(status), 0);
464 child_exited = true;
465 break;
466 }
467 Ok(None) => {
468 // Child still running, continue polling
469 std::thread::sleep(Duration::from_millis(50));
470 }
471 Err(e) => {
472 panic!("waitpid_nohang failed: {}", e);
473 }
474 }
475 }
476
477 assert!(child_exited, "Child should have exited");
478 assert!(
479 iterations > 1,
480 "Should have polled at least twice (child was running)"
481 );
482 }
483 Ok(Fork::Child) => {
484 // Child runs for a bit then exits
485 std::thread::sleep(Duration::from_millis(150));
486 exit(0);
487 }
488 Err(_) => panic!("Fork failed"),
489 }
490 }
491
492 #[test]
493 fn test_waitpid_nohang_invalid_pid() {
494 // Tests that waitpid_nohang returns error for invalid PID
495 // Expected behavior:
496 // 1. Call waitpid_nohang with non-existent PID
497 // 2. Should return Err with ECHILD
498 match fork() {
499 Ok(Fork::Parent(_)) => {
500 let result = waitpid_nohang(999_999);
501 assert!(result.is_err(), "Should fail for invalid PID");
502
503 let err = result.unwrap_err();
504 assert_eq!(
505 err.raw_os_error(),
506 Some(libc::ECHILD),
507 "Should return ECHILD for non-existent child"
508 );
509 }
510 Ok(Fork::Child) => exit(0),
511 Err(_) => panic!("Fork failed"),
512 }
513 }
514
515 #[test]
516 fn test_waitpid_nohang_multiple_children() {
517 // Tests checking multiple children with waitpid_nohang
518 // Expected behavior:
519 // 1. Create 3 children that exit at different times
520 // 2. Poll all children without blocking
521 // 3. Should be able to detect each child's exit independently
522 let mut children = vec![];
523
524 // Create 3 children
525 for i in 0_u32..3 {
526 match fork() {
527 Ok(Fork::Parent(child)) => {
528 children.push(child);
529 }
530 Ok(Fork::Child) => {
531 // Each child sleeps for a different duration
532 std::thread::sleep(Duration::from_millis(50 * u64::from(i + 1)));
533 exit(i.try_into().unwrap());
534 }
535 Err(_) => panic!("Fork {} failed", i),
536 }
537 }
538
539 // Poll children
540 let mut exited = [false; 3];
541 let mut all_exited = false;
542
543 for _ in 0..30 {
544 let mut count = 0;
545
546 for (idx, &pid) in children.iter().enumerate() {
547 if exited[idx] {
548 count += 1;
549 continue;
550 }
551
552 match waitpid_nohang(pid) {
553 Ok(Some(status)) => {
554 assert!(WIFEXITED(status));
555 exited[idx] = true;
556 count += 1;
557 }
558 Ok(None) => {
559 // Still running
560 }
561 Err(e) => {
562 panic!("waitpid_nohang failed for child {}: {}", pid, e);
563 }
564 }
565 }
566
567 if count == 3 {
568 all_exited = true;
569 break;
570 }
571
572 std::thread::sleep(Duration::from_millis(20));
573 }
574
575 assert!(all_exited, "All children should have exited");
576 }
577
578 #[test]
579 fn test_waitpid_nohang_returns_option() {
580 // Tests the return type of waitpid_nohang is Option<c_int>
581 // Expected behavior:
582 // 1. Verify type signature
583 // 2. Verify we can pattern match on Option
584 match fork() {
585 Ok(Fork::Parent(child)) => {
586 // Type annotation to verify signature
587 let result: std::io::Result<Option<libc::c_int>> = waitpid_nohang(child);
588
589 match result {
590 Ok(Some(_status)) => {
591 // Child exited quickly
592 }
593 Ok(None) => {
594 // Child still running - wait for it
595 waitpid(child).expect("waitpid failed");
596 }
597 Err(e) => {
598 panic!("Unexpected error: {}", e);
599 }
600 }
601 }
602 Ok(Fork::Child) => exit(0),
603 Err(_) => panic!("Fork failed"),
604 }
605 }
606
607 #[test]
608 fn test_waitpid_nohang_vs_blocking() {
609 // Tests the difference between waitpid and waitpid_nohang
610 // Expected behavior:
611 // 1. waitpid_nohang returns immediately
612 // 2. waitpid blocks until child exits
613 match fork() {
614 Ok(Fork::Parent(child)) => {
615 use std::time::Instant;
616
617 // Non-blocking check should return immediately
618 let start = Instant::now();
619 match waitpid_nohang(child) {
620 Ok(None) => {
621 // Expected: child still running
622 let elapsed = start.elapsed();
623 assert!(
624 elapsed < Duration::from_millis(50),
625 "waitpid_nohang should return immediately, took {:?}",
626 elapsed
627 );
628 }
629 Ok(Some(_)) => {
630 panic!("Child exited too quickly");
631 }
632 Err(e) => {
633 panic!("waitpid_nohang failed: {}", e);
634 }
635 }
636
637 // Now wait for child to finish (blocking)
638 let status = waitpid(child).expect("waitpid failed");
639 assert!(WIFEXITED(status));
640 }
641 Ok(Fork::Child) => {
642 // Child sleeps to ensure parent's nohang check happens first
643 std::thread::sleep(Duration::from_millis(100));
644 exit(0);
645 }
646 Err(_) => panic!("Fork failed"),
647 }
648 }