### Get Current Process Handle Source: https://docs.rs/win32job/latest/win32job/utils/fn.get_current_process.html Returns a pseudo handle to the current process. Refer to Microsoft Docs for more details. ```rust pub fn get_current_process() -> isize ``` -------------------------------- ### Get Current Process Source: https://docs.rs/win32job/latest/win32job/utils/fn.get_current_process.html Retrieves a pseudo handle to the current process. Refer to Microsoft Docs for more details. ```APIDOC ## GET /utils/get_current_process ### Description Returns a pseudo handle to the current process. ### Method GET ### Endpoint /utils/get_current_process ### Response #### Success Response (200) - **handle** (isize) - A pseudo handle to the current process. ``` -------------------------------- ### Get Process Affinity Mask Source: https://docs.rs/win32job/latest/win32job/utils/fn.get_process_affinity_mask.html Retrieves the process affinity mask for the specified process and the system affinity mask for the system. ```APIDOC ## get_process_affinity_mask ### Description Retrieves the process affinity mask for the specified process and the system affinity mask for the system. See also Microsoft Docs for this function. ### Method GET (Conceptual - this is a function call, not a direct HTTP endpoint) ### Endpoint win32job::utils::get_process_affinity_mask ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None (This is a function call) ### Response #### Success Response (200) - **(usize, usize)** - A tuple containing the process affinity mask and the system affinity mask. #### Response Example ```json { "process_affinity_mask": 1, "system_affinity_mask": 15 } ``` ### Error Handling - **Error**: If the function fails to retrieve the affinity masks. ``` -------------------------------- ### Get Current Process Handle Source: https://docs.rs/win32job/latest/src/win32job/utils.rs.html Retrieves a pseudo handle to the current process. This is a wrapper around the Windows API GetCurrentProcess function. ```APIDOC ## GET /utils/get_current_process ### Description Retrieves a pseudo handle to the current process. ### Method GET ### Endpoint /utils/get_current_process ### Parameters None ### Request Body None ### Response #### Success Response (200) - **handle** (isize) - A pseudo handle to the current process. #### Response Example ```json { "handle": 0 } ``` ``` -------------------------------- ### Get Current Process Handle Source: https://docs.rs/win32job/latest/src/win32job/utils.rs.html Returns a pseudo handle to the current process. This is useful for subsequent API calls that require a process handle. ```rust use std::{io, mem}; use windows::Win32::System::Threading::GetCurrentProcess; pub fn get_current_process() -> isize { unsafe { GetCurrentProcess() }.0 as _ } ``` -------------------------------- ### Get Process Memory Info Source: https://docs.rs/win32job/latest/src/win32job/utils.rs.html Retrieves detailed memory usage information for a specified process. This function wraps the Windows API GetProcessMemoryInfo. ```APIDOC ## GET /utils/get_process_memory_info ### Description Retrieves information about the memory usage of the specified process. ### Method GET ### Endpoint /utils/get_process_memory_info ### Parameters #### Query Parameters - **process_handle** (isize) - Required - A handle to the process whose memory usage is to be queried. ### Request Body None ### Response #### Success Response (200) - **page_fault_count** (u32) - The number of page faults that occurred for the process. - **peak_working_set_size** (usize) - The maximum number of bytes that the process has ever had in its working set. - **working_set_size** (usize) - The current number of bytes in the working set of the process. - **quota_peak_paged_pool_usage** (usize) - The maximum number of bytes that the process has ever allocated for its paged pool. - **quota_paged_pool_usage** (usize) - The current number of bytes that the process has allocated for its paged pool. - **quota_peak_non_paged_pool_usage** (usize) - The maximum number of bytes that the process has ever allocated for its nonpaged pool. - **quota_non_paged_pool_usage** (usize) - The current number of bytes that the process has allocated for its nonpaged pool. - **pagefile_usage** (usize) - The current number of bytes that the process has committed for its page file. - **peak_pagefile_usage** (usize) - The maximum number of bytes that the process has committed for its page file at any one time. - **private_usage** (usize) - The current number of bytes that the process is using for its private pages. #### Response Example ```json { "page_fault_count": 100, "peak_working_set_size": 1024000, "working_set_size": 512000, "quota_peak_paged_pool_usage": 200000, "quota_paged_pool_usage": 100000, "quota_peak_non_paged_pool_usage": 50000, "quota_non_paged_pool_usage": 25000, "pagefile_usage": 300000, "peak_pagefile_usage": 400000, "private_usage": 250000 } ``` ``` -------------------------------- ### Get Process Affinity Mask Source: https://docs.rs/win32job/latest/src/win32job/utils.rs.html Retrieves the process affinity mask and the system affinity mask for the specified process. Returns a tuple of two usize values representing the masks, or an I/O error. ```rust use std::{io, mem}; use windows::Win32::System::Threading::GetProcessAffinityMask; pub fn get_process_affinity_mask(process_handle: isize) -> Result<(usize, usize), io::Error> { let mut process_affinity_mask = 0usize; let mut system_affinity_mask = 0usize; unsafe { GetProcessAffinityMask( windows::Win32::Foundation::HANDLE(process_handle as _), &mut process_affinity_mask as *mut _, &mut system_affinity_mask as *mut _, ) } .map_err(|e| e.into()) .map(|_| (process_affinity_mask, system_affinity_mask)) ``` -------------------------------- ### Get Process Memory Information Source: https://docs.rs/win32job/latest/src/win32job/utils.rs.html Retrieves detailed memory usage information for a given process handle. Requires the process handle as input and returns a ProcessMemoryCounters struct or an I/O error. ```rust use std::{io, mem}; use windows::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; #[derive(Debug, Clone)] pub struct ProcessMemoryCounters { pub page_fault_count: u32, pub peak_working_set_size: usize, pub working_set_size: usize, pub quota_peak_paged_pool_usage: usize, pub quota_paged_pool_usage: usize, pub quota_peak_non_paged_pool_usage: usize, pub quota_non_paged_pool_usage: usize, pub pagefile_usage: usize, pub peak_pagefile_usage: usize, pub private_usage: usize, } pub fn get_process_memory_info(process_handle: isize) -> Result { let mut counters = PROCESS_MEMORY_COUNTERS_EX::default(); unsafe { GetProcessMemoryInfo( windows::Win32::Foundation::HANDLE(process_handle as _), &mut counters as *mut _ as *mut _, mem::size_of_val(&counters) as u32, ) }?; Ok(ProcessMemoryCounters { page_fault_count: counters.PageFaultCount, peak_working_set_size: counters.PeakWorkingSetSize, working_set_size: counters.WorkingSetSize, quota_peak_paged_pool_usage: counters.QuotaPeakPagedPoolUsage, quota_paged_pool_usage: counters.QuotaPagedPoolUsage, quota_peak_non_paged_pool_usage: counters.QuotaPeakNonPagedPoolUsage, quota_non_paged_pool_usage: counters.QuotaNonPagedPoolUsage, pagefile_usage: counters.PagefileUsage, peak_pagefile_usage: counters.PeakPagefileUsage, private_usage: counters.PrivateUsage, }) } ``` -------------------------------- ### Get Job Handle Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Retrieves the underlying handle to the job object. The handle will be automatically closed when the Job object is dropped. Use `into_handle` if you need to manage the handle's lifecycle manually. ```rust pub fn handle(&self) -> isize ``` -------------------------------- ### Configure and Assign Job Limits Source: https://docs.rs/win32job Demonstrates creating a job with specific limits using ExtendedLimitInfo and assigning the current process to it. ```rust use win32job::*; let mut info = ExtendedLimitInfo::new(); info.limit_working_memory(1 * 1024 * 1024, 4 * 1024 * 1024) .limit_priority_class(PriorityClass::BelowNormal); let job = Job::create_with_limit_info(&mut info)?; job.assign_current_process()?; ``` ```rust use win32job::*; let job = Job::create()?; let mut info = job.query_extended_limit_info()?; info.limit_working_memory(1 * 1024 * 1024, 4 * 1024 * 1024) .limit_priority_class(PriorityClass::BelowNormal); job.set_extended_limit_info(&mut info)?; job.assign_current_process()?; ``` -------------------------------- ### Configure Job Object Limits with ExtendedLimitInfo Source: https://docs.rs/win32job/latest/src/win32job/lib.rs.html Use this snippet to create a new job object and immediately configure its limits, such as working memory and priority class. This is a concise way to set up a job with specific constraints. ```rust use win32job::* # fn main() -> Result<(), JobError> { let mut info = ExtendedLimitInfo::new() info.limit_working_memory(1 * 1024 * 1024, 4 * 1024 * 1024) .limit_priority_class(PriorityClass::BelowNormal); let job = Job::create_with_limit_info(&mut info)?; job.assign_current_process()?; # info.clear_limits(); # job.set_extended_limit_info(&mut info)?; # Ok(()) # } ``` -------------------------------- ### Initialize ExtendedLimitInfo Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Creates a new `ExtendedLimitInfo` struct with default values, meaning no limits are initially set. ```rust pub fn new() -> Self { let inner = Default::default(); ExtendedLimitInfo(inner) } ``` -------------------------------- ### Query and Set Job Object Limits Source: https://docs.rs/win32job/latest/src/win32job/lib.rs.html This snippet demonstrates how to first create a job object, then query its existing extended limit information, modify it, and finally set the updated limits back to the job. This is useful when you need to inspect or modify limits on an existing job. ```rust use win32job::* # fn main() -> Result<(), JobError> { let job = Job::create()?; let mut info = job.query_extended_limit_info()?; info.limit_working_memory(1 * 1024 * 1024, 4 * 1024 * 1024) .limit_priority_class(PriorityClass::BelowNormal); job.set_extended_limit_info(&mut info)?; job.assign_current_process()?; # info.clear_limits(); # job.set_extended_limit_info(&mut info)?; # Ok(()) # } ``` -------------------------------- ### ExtendedLimitInfo Configuration Methods Source: https://docs.rs/win32job/latest/win32job/struct.ExtendedLimitInfo.html Methods for configuring various limits on a job object, such as memory, priority, and process breakaway behavior. ```APIDOC ## ExtendedLimitInfo Configuration ### Description Methods to configure limits for a job object. These methods return a mutable reference to the struct, allowing for method chaining. ### Methods - **new()** -> Self: Creates an empty ExtendedLimitInfo object. - **limit_working_memory(min: usize, max: usize)** -> &mut Self: Sets min/max working set sizes. - **limit_kill_on_job_close()** -> &mut Self: Terminates processes when the job handle is closed. - **limit_breakaway_ok()** -> &mut Self: Allows child processes to not be associated with the job. - **limit_silent_breakaway_ok()** -> &mut Self: Allows child processes to be created without job association. - **limit_priority_class(priority_class: PriorityClass)** -> &mut Self: Sets the priority class for all processes in the job. - **limit_scheduling_class(scheduling_class: u8)** -> &mut Self: Sets the scheduling class (0-9). - **limit_affinity(affinity: usize)** -> &mut Self: Sets processor affinity. - **clear_limits()** -> &mut Self: Clears all configured limits. ``` -------------------------------- ### Create Job with Limit Info Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Creates an anonymous job object and immediately sets its limits using the provided ExtendedLimitInfo. Use this when you need to configure job limits upon creation. ```rust pub fn create_with_limit_info( info: &ExtendedLimitInfo, ) -> Result ``` -------------------------------- ### Job Management API Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Methods for creating, configuring, and managing Windows Job objects. ```APIDOC ## Job Object Methods ### create() - **Description**: Create an anonymous job object. - **Returns**: Result ### create_with_limit_info(info: &ExtendedLimitInfo) - **Description**: Create an anonymous job object and sets its limit according to `info`. - **Parameters**: info (ExtendedLimitInfo) - Required - **Returns**: Result ### handle() - **Description**: Return the underlying handle to the job. Note that this handle will be closed once the `Job` object is dropped. - **Returns**: isize ### into_handle() - **Description**: Return the underlying handle to the job, consuming the job. Note that the handle will NOT be closed. - **Returns**: isize ### query_extended_limit_info() - **Description**: Return basic and extended limit information for a job object. - **Returns**: Result ### set_extended_limit_info(info: &ExtendedLimitInfo) - **Description**: Set the basic and extended limit information for a job object. - **Parameters**: info (ExtendedLimitInfo) - Required - **Returns**: Result<(), JobError> ### assign_process(proc_handle: isize) - **Description**: Assigns a process to the job object. - **Parameters**: proc_handle (isize) - Required - **Returns**: Result<(), JobError> ### assign_current_process() - **Description**: Assigns the current process to the job object. - **Returns**: Result<(), JobError> ### query_process_id_list() - **Description**: Return all the process identifiers for a job object. - **Returns**: Result, JobError> ``` -------------------------------- ### win32job Structs and Enums Source: https://docs.rs/win32job/latest/win32job/all.html Overview of the primary data structures and error types provided by the win32job crate. ```APIDOC ## Structs - **ExtendedLimitInfo**: Represents extended limit information for a job object. - **Job**: The primary handle for interacting with a Windows Job Object. - **utils::ProcessMemoryCounters**: Contains memory usage statistics for a process. ## Enums - **JobError**: Represents errors that can occur during job object operations. - **PriorityClass**: Defines the scheduling priority class for processes within a job. ``` -------------------------------- ### Manage Windows Job Objects Source: https://docs.rs/win32job/latest/src/win32job/job.rs.html The Job struct wraps a Windows HANDLE to a job object. It provides methods for creation, limit configuration, and process assignment. ```rust use windows::{ core::PCWSTR, Win32::{ Foundation::{CloseHandle, HANDLE}, System::JobObjects::{ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject, }, }, }; use crate::error::JobError; use crate::limits::ExtendedLimitInfo; use std::{ffi::c_void, mem}; pub use crate::utils::get_current_process; #[derive(Debug)] pub struct Job { pub(crate) handle: HANDLE, } unsafe impl Send for Job {} unsafe impl Sync for Job {} impl Job { /// Create an anonymous job object. pub fn create() -> Result { unsafe { CreateJobObjectW(None, PCWSTR::null()) } .map_err(|e| JobError::CreateFailed(e.into())) .map(|handle| Self { handle }) } /// Create an anonymous job object and sets it's limit according to `info`. pub fn create_with_limit_info(info: &ExtendedLimitInfo) -> Result { let job = Self::create()?; job.set_extended_limit_info(info)?; Ok(job) } /// Return the underlying handle to the job. /// Note that this handle will be closed once the `Job` object is dropped. pub fn handle(&self) -> isize { self.handle.0 as _ } /// Return the underlying handle to the job, consuming the job. /// Note that the handle will NOT be closed, so it is the caller's responsibly to close it. pub fn into_handle(self) -> isize { let job = mem::ManuallyDrop::new(self); job.handle.0 as _ } /// Return basic and extended limit information for a job object. /// See also [Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_extended_limit_information). pub fn query_extended_limit_info(&self) -> Result { let mut info = ExtendedLimitInfo::default(); unsafe { QueryInformationJobObject( Some(self.handle), JobObjectExtendedLimitInformation, &mut info.0 as *mut _ as *mut c_void, mem::size_of_val(&info.0) as u32, None, ) } .map_err(|e| JobError::GetInfoFailed(e.into()))?; Ok(info) } /// Set the basic and extended limit information for a job object. pub fn set_extended_limit_info(&self, info: &ExtendedLimitInfo) -> Result<(), JobError> { unsafe { SetInformationJobObject( self.handle, JobObjectExtendedLimitInformation, &info.0 as *const _ as *const c_void, mem::size_of_val(&info.0) as u32, ) .map_err(|e| JobError::SetInfoFailed(e.into())) } } /// Assigns a process to the job object. /// See also [Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-assignprocesstojobobject). pub fn assign_process(&self, proc_handle: isize) -> Result<(), JobError> { unsafe { AssignProcessToJobObject(self.handle, HANDLE(proc_handle as _)) } .map_err(|e| JobError::AssignFailed(e.into())) } /// Assigns the current process to the job object. pub fn assign_current_process(&self) -> Result<(), JobError> { let current_proc_handle = get_current_process(); self.assign_process(current_proc_handle) } } impl Drop for Job { fn drop(&mut self) { unsafe { let _ = CloseHandle(self.handle); } } } ``` ```rust #[cfg(test)] mod tests { use windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_WORKINGSET; use crate::Job; #[test] fn it_works() { let job = Job::create().unwrap(); let mut info = job.query_extended_limit_info().unwrap(); assert_eq!(info.0.BasicLimitInformation.LimitFlags.0, 0); // This is the default. assert_eq!(info.0.BasicLimitInformation.SchedulingClass, 5); info.0.BasicLimitInformation.MinimumWorkingSetSize = 1 * 1024 * 1024; info.0.BasicLimitInformation.MaximumWorkingSetSize = 4 * 1024 * 1024; info.0.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_WORKINGSET; job.set_extended_limit_info(&mut info).unwrap(); // Clear limits. info.0.BasicLimitInformation.LimitFlags.0 = 0; job.set_extended_limit_info(&mut info).unwrap(); } } ``` -------------------------------- ### win32job Utility Functions Source: https://docs.rs/win32job/latest/win32job/all.html Utility functions for retrieving information about the current process and system resources. ```APIDOC ## Functions - **utils::get_current_process**: Retrieves a handle to the current process. - **utils::get_process_affinity_mask**: Gets the processor affinity mask for a specified process. - **utils::get_process_memory_info**: Retrieves memory usage information for a specified process. ``` -------------------------------- ### Query Job Limit Information Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Retrieves basic and extended limit information for a job object. Refer to Microsoft Docs for detailed explanations of the returned information. ```rust pub fn query_extended_limit_info(&self) -> Result ``` -------------------------------- ### Set Job Limit Information Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Sets the basic and extended limit information for an existing job object. Ensure the provided `ExtendedLimitInfo` is correctly configured. ```rust pub fn set_extended_limit_info( &self, info: &ExtendedLimitInfo, ) -> Result<(), JobError> ``` -------------------------------- ### Query process identifiers for a job object Source: https://docs.rs/win32job/latest/src/win32job/query.rs.html Retrieves a list of process IDs associated with the job. Note that the current implementation is limited to 1024 processes. ```rust 1use std::{ffi::c_void, mem}; 2use windows::Win32::System::JobObjects::{ 3 JobObjectBasicProcessIdList, QueryInformationJobObject, JOBOBJECT_BASIC_PROCESS_ID_LIST, 4}; 5 6use crate::{Job, JobError}; 7 8#[repr(C)] 9#[derive(Debug)] 10struct ProcessIdList { 11 header: JOBOBJECT_BASIC_PROCESS_ID_LIST, 12 list: [usize; 1024], 13} 14 15impl Job { 16 /// Return all the process identifiers for a job object. 17 /// If the job is nested, the process identifier list consists of all processes 18 /// associated with the job and its child jobs. 19 pub fn query_process_id_list(&self) -> Result, JobError> { 20 // TODO: We will get an error if there are more than 1024 processes in the job. 21 // This can be fixed by calling `QueryInformationJobObject` a second time, 22 // with a bigger list with the correct size (as returned from the first call). 23 let mut proc_id_list = ProcessIdList { 24 header: Default::default(), 25 list: [0usize; 1024], 26 }; 27 28 unsafe { 29 QueryInformationJobObject( 30 Some(self.handle), 31 JobObjectBasicProcessIdList, 32 &mut proc_id_list as *mut _ as *mut c_void, 33 mem::size_of_val(&proc_id_list) as u32, 34 None, 35 ) 36 } 37 .map_err(|e| JobError::GetInfoFailed(e.into()))?; 38 39 let list = proc_id_list 40 .header 41 .ProcessIdList 42 .into_iter() 43 .chain(proc_id_list.list) 44 .take(proc_id_list.header.NumberOfProcessIdsInList as usize) 45 .collect(); 46 47 Ok(list) 48 } 49} 50 51#[cfg(test)] 52mod tests { 53 use crate::Job; 54 55 #[test] 56 fn query_proc_id() { 57 let job = Job::create().unwrap(); 58 59 let pids = job.query_process_id_list().unwrap(); 60 assert_eq!(pids, []); 61 62 job.assign_current_process().unwrap(); 63 64 let pids = job.query_process_id_list().unwrap(); 65 66 let current_process_id = std::process::id() as usize; 67 68 // It's not equal to 1 because sometime we "catch" `rusty_fork_test` sub procs. 69 assert!(pids.len() >= 1); 70 71 assert!(pids.contains(¤t_process_id)); 72 } 73} ``` -------------------------------- ### Implement Debug for Job Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a Debug implementation for the Job struct, allowing it to be formatted for debugging purposes using the given formatter. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### ExtendedLimitInfo Struct and Methods Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html The ExtendedLimitInfo struct provides a convenient way to set and manage limits for Win32 job objects. It wraps the JOBOBJECT_EXTENDED_LIMIT_INFORMATION structure and offers methods for specific limit configurations. ```APIDOC ## ExtendedLimitInfo ### Description Contains basic and extended limit information for a job object, with helper methods for easy limit manipulation. To apply limits, pass the instance of this struct to `Job::create_with_limit_info` or `job.set_extended_limit_info`. ### Methods #### `new()` * **Description**: Return an empty extended info object, without any limits. * **Returns**: An instance of `ExtendedLimitInfo` with no limits set. #### `limit_working_memory(min: usize, max: usize)` * **Description**: Causes all processes associated with the job to use the same minimum and maximum working set sizes. * **Parameters**: * `min` (usize) - The minimum working set size in bytes. * `max` (usize) - The maximum working set size in bytes. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_kill_on_job_close()` * **Description**: Causes all processes associated with the job to terminate when the last handle to the job is closed. Note that dropping the `Job` struct closes this handle, and if it's the only handle to the job, the current process will terminate if it's assigned to that job. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_breakaway_ok()` * **Description**: If any process associated with the job creates a child process using this flag, the child process is not associated with the job. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_silent_breakaway_ok()` * **Description**: Allows any process associated with the job to create child processes that are not associated with the job. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_priority_class(priority_class: PriorityClass)` * **Description**: Causes all processes associated with the job to use the same priority class. Note: Processes and threads cannot modify their priority class. The calling process must enable the `SE_INC_BASE_PRIORITY_NAME` privilege. * **Parameters**: * `priority_class` (PriorityClass) - The desired priority class. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_scheduling_class(scheduling_class: u8)` * **Description**: Causes all processes in the job to use the same scheduling class. The valid values are 0 to 9. Use 0 for the least favorable scheduling class relative to other threads, and 9 for the most favorable scheduling class relative to other threads. By default, this value is 5. Note: To use a scheduling class greater than 5, the calling process must enable the `SE_INC_BASE_PRIORITY_NAME` privilege. * **Parameters**: * `scheduling_class` (u8) - The scheduling class value (0-9). * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `limit_affinity(affinity: usize)` * **Description**: Causes all processes associated with the job to use the same processor affinity. * **Parameters**: * `affinity` (usize) - The processor affinity mask. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. #### `clear_limits()` * **Description**: Clear all limits set on the job object. * **Returns**: A mutable reference to the `ExtendedLimitInfo` instance. ### Enum `PriorityClass` * **Description**: Represents the different priority classes available for processes. * **Values**: * `Normal` * `Idle` * `High` * `Realtime` * `BelowNormal` * `AboveNormal` ``` -------------------------------- ### Test Working Memory Limits Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Verifies that working set memory limits are correctly applied to the assigned process. ```rust rusty_fork_test! { #[test] fn working_mem_limits() { let job = Job::create().unwrap(); let mut info = job.query_extended_limit_info().unwrap(); let min = 1 * 1024 * 1024; let max = 4 * 1024 * 1024; info.limit_working_memory(min, max); job.set_extended_limit_info(&mut info).unwrap(); job.assign_current_process().unwrap(); let test_vec_size = max * 4; let mut big_vec: Vec = Vec::with_capacity(test_vec_size); big_vec.resize_with(test_vec_size, || 1); let memory_info = get_process_memory_info(get_current_process()).unwrap(); assert!(memory_info.working_set_size <= max * 2); info.clear_limits(); job.set_extended_limit_info(&mut info).unwrap(); } } ``` -------------------------------- ### Job Object Management API Source: https://docs.rs/win32job/latest/src/win32job/job.rs.html API endpoints for creating, querying, and modifying Windows Job Objects. ```APIDOC ## POST /job/create ### Description Creates an anonymous job object. ### Method POST ### Endpoint /job/create ### Response #### Success Response (200) - **handle** (isize) - The handle to the newly created job object. #### Response Example ```json { "handle": 12345 } ``` ## POST /job/create_with_limit_info ### Description Creates an anonymous job object and sets its limit information. ### Method POST ### Endpoint /job/create_with_limit_info ### Parameters #### Request Body - **info** (ExtendedLimitInfo) - Required - The extended limit information to apply to the job object. ### Request Example ```json { "info": { "minimum_working_set_size": 1048576, "maximum_working_set_size": 4194304, "limit_flags": 1 } } ``` ### Response #### Success Response (200) - **handle** (isize) - The handle to the newly created and configured job object. #### Response Example ```json { "handle": 12345 } ``` ## GET /job/{handle}/handle ### Description Returns the underlying handle to the job object. The handle will be closed when the `Job` object is dropped. ### Method GET ### Endpoint /job/{handle}/handle ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. ### Response #### Success Response (200) - **handle_value** (isize) - The value of the job object handle. #### Response Example ```json { "handle_value": 12345 } ``` ## GET /job/{handle}/into_handle ### Description Returns the underlying handle to the job object, consuming the job object. The handle will NOT be closed, and it is the caller's responsibility to close it. ### Method GET ### Endpoint /job/{handle}/into_handle ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. ### Response #### Success Response (200) - **handle_value** (isize) - The value of the job object handle. #### Response Example ```json { "handle_value": 12345 } ``` ## GET /job/{handle}/query_extended_limit_info ### Description Retrieves basic and extended limit information for a job object. ### Method GET ### Endpoint /job/{handle}/query_extended_limit_info ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. ### Response #### Success Response (200) - **info** (ExtendedLimitInfo) - The extended limit information for the job object. #### Response Example ```json { "info": { "minimum_working_set_size": 1048576, "maximum_working_set_size": 4194304, "limit_flags": 1 } } ``` ## PUT /job/{handle}/set_extended_limit_info ### Description Sets the basic and extended limit information for a job object. ### Method PUT ### Endpoint /job/{handle}/set_extended_limit_info ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. #### Request Body - **info** (ExtendedLimitInfo) - Required - The new extended limit information to set. ### Request Example ```json { "info": { "minimum_working_set_size": 1048576, "maximum_working_set_size": 4194304, "limit_flags": 1 } } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example ```json { "message": "Extended limit information updated successfully." } ``` ## POST /job/{handle}/assign_process ### Description Assigns a process to the job object. ### Method POST ### Endpoint /job/{handle}/assign_process ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. #### Request Body - **proc_handle** (isize) - Required - The handle of the process to assign. ### Request Example ```json { "proc_handle": 54321 } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful assignment. #### Response Example ```json { "message": "Process assigned to job successfully." } ``` ## POST /job/{handle}/assign_current_process ### Description Assigns the current process to the job object. ### Method POST ### Endpoint /job/{handle}/assign_current_process ### Parameters #### Path Parameters - **handle** (isize) - Required - The handle of the job object. ### Response #### Success Response (200) - **message** (string) - Indicates successful assignment. #### Response Example ```json { "message": "Current process assigned to job successfully." } ``` ``` -------------------------------- ### Implement Any Trait Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a blanket implementation of the `Any` trait for any type `T` that is `'static` and `?Sized`. This allows for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Define ExtendedLimitInfo struct Source: https://docs.rs/win32job/latest/win32job/struct.ExtendedLimitInfo.html The internal structure definition for ExtendedLimitInfo. ```rust pub struct ExtendedLimitInfo(/* private fields */); ``` -------------------------------- ### Create Anonymous Job Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Creates an anonymous job object. This is a basic way to instantiate a job object without any initial configuration. ```rust pub fn create() -> Result ``` -------------------------------- ### Implement Debug for JobError Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Provides a way to format the JobError enum for debugging purposes. ```rust impl Debug for JobError { fn fmt(&self, f: &mut Formatter<'_>) -> Result } ``` -------------------------------- ### Limit Scheduling Class Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Assigns a scheduling class (0-9) to all processes in the job. Higher values indicate more favorable scheduling. Requires `SE_INC_BASE_PRIORITY_NAME` privilege for classes above 5. Uses the `JOB_OBJECT_LIMIT_SCHEDULING_CLASS` flag. ```rust pub fn limit_scheduling_class(&mut self, scheduling_class: u8) -> &mut Self { self.0.BasicLimitInformation.SchedulingClass = scheduling_class as u32; self.0.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_SCHEDULING_CLASS; self } ``` -------------------------------- ### Implement From Trait Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a blanket implementation of the `From` trait for any type `T`. This allows conversion from `T` to `T` itself. ```rust fn from(t: T) -> T ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the Any trait for any type T. ```rust impl Any for T where T: 'static + ?Sized, { fn type_id(&self) -> TypeId } ``` -------------------------------- ### Implement TryInto Trait Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a blanket implementation of the `TryInto` trait for any type `T` where `U` implements `TryFrom`. This allows fallible conversion from `T` to `U`. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Implement TryFrom Trait Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a blanket implementation of the `TryFrom` trait for any type `T` where `U` implements `Into`. This allows fallible conversion from `U` to `T`. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Implement Borrow for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the Borrow trait for any type T. ```rust impl Borrow for T where T: ?Sized, { fn borrow(&self) -> &T } ``` -------------------------------- ### Implement Display for JobError Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Provides a user-friendly string representation for the JobError enum. ```rust impl Display for JobError { fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result } ``` -------------------------------- ### Implement Into for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the Into trait for converting a type T into a type U, where U implements From. ```rust impl Into for T where U: From, { fn into(self) -> U } ``` -------------------------------- ### get_process_memory_info Source: https://docs.rs/win32job/latest/win32job/utils/fn.get_process_memory_info.html Retrieves memory usage information for a given process handle. ```APIDOC ## get_process_memory_info ### Description Retrieves information about the memory usage of the specified process. ### Parameters #### Path Parameters - **process_handle** (isize) - Required - A handle to the process for which memory information is requested. ### Response #### Success Response (200) - **ProcessMemoryCounters** (Object) - Returns a structure containing memory usage statistics for the process. #### Error Response - **Error** (Object) - Returns an error if the memory information could not be retrieved. ``` -------------------------------- ### Limit Breakaway OK Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Allows processes within the job to create child processes that are not associated with the job. This uses the `JOB_OBJECT_LIMIT_BREAKAWAY_OK` flag. ```rust pub fn limit_breakaway_ok(&mut self) -> &mut Self { self.0.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_BREAKAWAY_OK; self } ``` -------------------------------- ### Implement From for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the From trait for converting a type T into itself. ```rust impl From for T { fn from(t: T) -> T } ``` -------------------------------- ### Implement TryFrom for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the TryFrom trait for attempting to convert a type U into a type T. ```rust impl TryFrom for T where U: Into, { type Error = Infallible; fn try_from(value: U) -> Result>::Error> } ``` -------------------------------- ### Implement TryInto for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the TryInto trait for attempting to convert a type T into a type U. ```rust impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> } ``` -------------------------------- ### Implement ToString for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the ToString trait for any type T that implements Display. ```rust impl ToString for T where T: Display + ?Sized, { fn to_string(&self) -> String } ``` -------------------------------- ### Assign Current Process to Job Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Assigns the current process (the one executing this code) to the job object. This is a convenient way to add the running process to a job without needing its handle explicitly. ```rust pub fn assign_current_process(&self) -> Result<(), JobError> ``` -------------------------------- ### Query Process ID List Source: https://docs.rs/win32job/latest/src/win32job/query.rs.html Retrieves a list of all process identifiers associated with a job object. If the job is nested, this includes processes from child jobs. ```APIDOC ## POST /query_process_id_list ### Description Retrieves all process identifiers for a job object. If the job is nested, the process identifier list consists of all processes associated with the job and its child jobs. ### Method POST ### Endpoint `/query_process_id_list` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "job_handle": "" } ``` ### Response #### Success Response (200) - **process_ids** (array[usize]) - A list of process identifiers. #### Response Example ```json { "process_ids": [1234, 5678, 9012] } ``` #### Error Response (500) - **error** (string) - Description of the error. #### Error Response Example ```json { "error": "Failed to query job information" } ``` ``` -------------------------------- ### Limit Working Memory Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Sets the minimum and maximum working set sizes for processes within the job. This requires the `JOB_OBJECT_LIMIT_WORKINGSET` flag to be set. ```rust pub fn limit_working_memory(&mut self, min: usize, max: usize) -> &mut Self { self.0.BasicLimitInformation.MinimumWorkingSetSize = min; self.0.BasicLimitInformation.MaximumWorkingSetSize = max; self.0.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_WORKINGSET; self } ``` -------------------------------- ### Implement Into Trait Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Provides a blanket implementation of the `Into` trait for any type `T` where `U` implements `From`. This allows conversion from `T` to `U`. ```rust fn into(self) -> U ``` -------------------------------- ### Limit Priority Class Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Sets a uniform priority class for all processes within the job. Requires the `SE_INC_BASE_PRIORITY_NAME` privilege for the calling process. Uses the `JOB_OBJECT_LIMIT_PRIORITY_CLASS` flag. ```rust pub fn limit_priority_class(&mut self, priority_class: PriorityClass) -> &mut Self { self.0.BasicLimitInformation.PriorityClass = priority_class as u32; self.0.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PRIORITY_CLASS; self } ``` -------------------------------- ### Implement BorrowMut for T Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Blanket implementation of the BorrowMut trait for any type T. ```rust impl BorrowMut for T where T: ?Sized, { fn borrow_mut(&mut self) -> &mut T } ``` -------------------------------- ### Test Priority Class Limits Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Validates that the priority class limit is correctly set and retrieved from the job object. ```rust rusty_fork_test! { #[test] fn priority_class_limits() { let job = Job::create().unwrap(); let mut info = job.query_extended_limit_info().unwrap(); info.limit_priority_class(PriorityClass::BelowNormal); job.set_extended_limit_info(&mut info).unwrap(); let info = job.query_extended_limit_info().unwrap(); assert_eq!(info.0.BasicLimitInformation.PriorityClass, PriorityClass::BelowNormal as u32); } } ``` -------------------------------- ### Implement From for Error Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Allows conversion of a JobError into a generic Error type. ```rust impl From for Error { fn from(value: JobError) -> Self } ``` -------------------------------- ### Test Scheduling Class Limits Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Validates that the scheduling class limit is correctly set and retrieved from the job object. ```rust rusty_fork_test! { #[test] fn scheduling_class_limits() { let job = Job::create().unwrap(); let mut info = job.query_extended_limit_info().unwrap(); info.limit_scheduling_class(1); job.set_extended_limit_info(&mut info).unwrap(); let info = job.query_extended_limit_info().unwrap(); assert_eq!(info.0.BasicLimitInformation.SchedulingClass, 1); } } ``` -------------------------------- ### Query Process ID List for Job Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Retrieves a list of all process identifiers associated with a job object. If the job is nested, this list includes processes from the job and all its child jobs. ```rust pub fn query_process_id_list(&self) -> Result, JobError> ``` -------------------------------- ### Assign Process to Job Source: https://docs.rs/win32job/latest/win32job/struct.Job.html Assigns a specified process, identified by its handle, to the job object. This operation is crucial for associating processes with job control policies. See also Microsoft Docs. ```rust pub fn assign_process(&self, proc_handle: isize) -> Result<(), JobError> ``` -------------------------------- ### JobError Trait Implementations Source: https://docs.rs/win32job/latest/win32job/enum.JobError.html Details the various trait implementations for the JobError enum, including Debug, Display, Error, and From for Error. ```APIDOC ## Trait Implementations ### impl Debug for JobError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. ### impl Display for JobError #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. ### impl Error for JobError #### fn source(&self) -> Option<&(dyn Error + 'static)> Returns the lower-level source of this error, if any. #### fn description(&self) -> &str Deprecated since 1.42.0: use the Display impl or to_string(). #### fn cause(&self) -> Option<&dyn Error> Deprecated since 1.33.0: replaced by Error::source, which can support downcasting. #### fn provide<'a>(&'a self, request: &mut Request<'a>) This is a nightly-only experimental API. (`error_generic_member_access`) Provides type-based access to context intended for error reports. ### impl From for Error #### fn from(value: JobError) -> Self Converts to this type from the input type. ``` -------------------------------- ### Define PriorityClass Enum Source: https://docs.rs/win32job/latest/src/win32job/limits.rs.html Defines an enum for Win32 priority classes, mapping them to their corresponding `u32` values. ```rust 1use windows::Win32::System::JobObjects::*; use windows::Win32::System::Threading::*; #[derive(Debug, Clone, Copy)] #[repr(u32)] pub enum PriorityClass { Normal = NORMAL_PRIORITY_CLASS.0, Idle = IDLE_PRIORITY_CLASS.0, High = HIGH_PRIORITY_CLASS.0, Realtime = REALTIME_PRIORITY_CLASS.0, BelowNormal = BELOW_NORMAL_PRIORITY_CLASS.0, AboveNormal = ABOVE_NORMAL_PRIORITY_CLASS.0, } ```