ante_exec/
process_group.rs1use std::io;
6
7#[cfg(target_os = "linux")]
8pub fn set_parent_death_signal(parent_pid: libc::pid_t) -> io::Result<()> {
13 if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) } == -1 {
14 return Err(io::Error::last_os_error());
15 }
16
17 if unsafe { libc::getppid() } != parent_pid {
18 unsafe {
19 libc::raise(libc::SIGTERM);
20 }
21 }
22
23 Ok(())
24}
25
26#[cfg(not(target_os = "linux"))]
27pub fn set_parent_death_signal(_parent_pid: i32) -> io::Result<()> {
29 Ok(())
30}
31
32#[cfg(unix)]
33pub fn detach_from_tty() -> io::Result<()> {
35 let result = unsafe { libc::setsid() };
36 if result == -1 {
37 let err = io::Error::last_os_error();
38 if err.raw_os_error() == Some(libc::EPERM) {
39 return set_process_group();
40 }
41 return Err(err);
42 }
43 Ok(())
44}
45
46#[cfg(not(unix))]
47pub fn detach_from_tty() -> io::Result<()> {
49 Ok(())
50}
51
52#[cfg(unix)]
53pub fn set_process_group() -> io::Result<()> {
57 let result = unsafe { libc::setpgid(0, 0) };
58 if result == -1 { Err(io::Error::last_os_error()) } else { Ok(()) }
59}
60
61#[cfg(not(unix))]
62pub fn set_process_group() -> io::Result<()> {
64 Ok(())
65}
66
67#[cfg(unix)]
68pub fn kill_by_pid(pid: u32) -> io::Result<()> {
70 use std::io::ErrorKind;
71
72 let pid = pid as libc::pid_t;
73 let pgid = unsafe { libc::getpgid(pid) };
74 if pgid == -1 {
75 let err = io::Error::last_os_error();
76 if err.kind() != ErrorKind::NotFound {
77 return Err(err);
78 }
79 return Ok(());
80 }
81
82 let result = unsafe { libc::killpg(pgid, libc::SIGKILL) };
83 if result == -1 {
84 let err = io::Error::last_os_error();
85 if err.kind() != ErrorKind::NotFound {
86 return Err(err);
87 }
88 }
89
90 Ok(())
91}
92
93#[cfg(not(unix))]
94pub fn kill_by_pid(_pid: u32) -> io::Result<()> {
96 Ok(())
97}
98
99#[cfg(unix)]
100pub fn kill_process_group(pgid: u32) -> io::Result<()> {
111 use std::io::ErrorKind;
112
113 if pgid <= 1 {
114 return Ok(());
115 }
116 let Ok(pgid) = libc::pid_t::try_from(pgid) else {
117 return Ok(());
118 };
119 if unsafe { libc::killpg(pgid, libc::SIGKILL) } == -1 {
120 let err = io::Error::last_os_error();
121 if err.kind() != ErrorKind::NotFound {
122 return Err(err);
123 }
124 }
125 Ok(())
126}
127
128#[cfg(not(unix))]
129pub fn kill_process_group(_pgid: u32) -> io::Result<()> {
131 Ok(())
132}
133
134#[cfg(unix)]
135pub fn process_group_is_alive(pgid: u32) -> bool {
144 if pgid <= 1 {
145 return false;
146 }
147 let Ok(pgid) = libc::pid_t::try_from(pgid) else {
148 return false;
149 };
150 if unsafe { libc::killpg(pgid, 0) } == 0 {
151 return true;
152 }
153 io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
154}
155
156#[cfg(not(unix))]
157pub fn process_group_is_alive(_pgid: u32) -> bool {
160 true
161}