char/avril

(wip) why'd you have to go and make things so complicaaaaated?

git clone https://git.t4t.associates/char/avril

Charlotte Somrearrange libs into lib and extensions into extsf4a0f5b

main
2.0 KiB62 linesraw
1use std::io;
2use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
3use windows_sys::Win32::System::JobObjects::*;
4
5pub(crate) struct Job(OwnedHandle);
6
7impl Job {
8    pub fn new(flags: u32) -> io::Result<Self> {
9        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
10        if handle.is_null() {
11            return Err(io::Error::last_os_error());
12        }
13        let job = Self(unsafe { OwnedHandle::from_raw_handle(handle) });
14        let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
15        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | flags;
16        if unsafe {
17            SetInformationJobObject(
18                job.as_raw_handle(),
19                JobObjectExtendedLimitInformation,
20                (&raw const limits).cast(),
21                std::mem::size_of_val(&limits) as u32,
22            )
23        } == 0
24        {
25            return Err(io::Error::last_os_error());
26        }
27        Ok(job)
28    }
29
30    pub fn alive(&self) -> io::Result<bool> {
31        let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { std::mem::zeroed() };
32        if unsafe {
33            QueryInformationJobObject(
34                self.as_raw_handle(),
35                JobObjectBasicAccountingInformation,
36                (&raw mut accounting).cast(),
37                std::mem::size_of_val(&accounting) as u32,
38                std::ptr::null_mut(),
39            )
40        } == 0
41        {
42            return Err(io::Error::last_os_error());
43        }
44        Ok(accounting.ActiveProcesses > 0)
45    }
46
47    pub fn terminate(&self) -> io::Result<bool> {
48        if !self.alive()? {
49            return Ok(false);
50        }
51        if unsafe { TerminateJobObject(self.as_raw_handle(), 1) } == 0 {
52            return Err(io::Error::last_os_error());
53        }
54        Ok(true)
55    }
56}
57
58impl AsRawHandle for Job {
59    fn as_raw_handle(&self) -> RawHandle {
60        self.0.as_raw_handle()
61    }
62}