1 // run-pass
2 // ignore-emscripten no processes
3 // ignore-sgx no processes
4 // ignore-vxworks no 'ps'
5 
6 #![feature(rustc_private)]
7 
8 extern crate libc;
9 
10 use std::process::Command;
11 
12 // The output from "ps -A -o pid,ppid,args" should look like this:
13 //   PID  PPID COMMAND
14 //     1     0 /sbin/init
15 //     2     0 [kthreadd]
16 // ...
17 //  6076  9064 /bin/zsh
18 // ...
19 //  7164  6076 ./spawn-failure
20 //  7165  7164 [spawn-failure] <defunct>
21 //  7166  7164 [spawn-failure] <defunct>
22 // ...
23 //  7197  7164 [spawn-failure] <defunct>
24 //  7198  7164 ps -A -o pid,ppid,command
25 // ...
26 
27 #[cfg(unix)]
find_zombies()28 fn find_zombies() {
29     let my_pid = unsafe { libc::getpid() };
30 
31     // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
32     let ps_cmd_output = Command::new("ps").args(&["-A", "-o", "pid,ppid,args"]).output().unwrap();
33     let ps_output = String::from_utf8_lossy(&ps_cmd_output.stdout);
34 
35     for (line_no, line) in ps_output.split('\n').enumerate() {
36         if 0 < line_no && 0 < line.len() &&
37            my_pid == line.split(' ').filter(|w| 0 < w.len()).nth(1)
38                          .expect("1st column should be PPID")
39                          .parse().ok()
40                          .expect("PPID string into integer") &&
41            line.contains("defunct") {
42             panic!("Zombie child {}", line);
43         }
44     }
45 }
46 
47 #[cfg(windows)]
find_zombies()48 fn find_zombies() { }
49 
main()50 fn main() {
51     let too_long = format!("/NoSuchCommand{:0300}", 0u8);
52 
53     let _failures = (0..100).map(|_| {
54         let mut cmd = Command::new(&too_long);
55         let failed = cmd.spawn();
56         assert!(failed.is_err(), "Make sure the command fails to spawn(): {:?}", cmd);
57         failed
58     }).collect::<Vec<_>>();
59 
60     find_zombies();
61     // then _failures goes out of scope
62 }
63