1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
///
#[cfg(feature = "process")]
pub mod process {
/// A struct representing information about a process, including its PID and name.
#[derive(Debug, Clone, Default)]
pub struct ProcessInfo {
/// The process ID.
pub pid: u64,
/// The process name.
pub name: String,
}
/// todo: implement
#[allow(warnings)]
#[cfg(target_os = "macos")]
pub fn get_all_process_name_and_pid() -> Vec<ProcessInfo> {
use cocoa::appkit;
todo!()
}
/// Retrieves information about all running processes on a Windows system.
///
/// # Examples
///
/// ```
/// let processes: Vec<ProcessInfo> = get_all_process_name_and_pid();
/// for process in processes {
/// println!("Process ID: {}, Name: {}", process.pid, process.name);
/// }
/// ```
#[cfg(target_os = "windows")]
pub fn get_all_process_name_and_pid() -> Vec<ProcessInfo> {
use std::mem;
use winapi::shared::minwindef::TRUE;
use winapi::um::tlhelp32::{
Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
};
let mut res = vec![];
unsafe {
let snapshot = winapi::um::tlhelp32::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snapshot == winapi::um::handleapi::INVALID_HANDLE_VALUE {
panic!("Failed to create snapshot");
}
let mut process_entry: PROCESSENTRY32W = mem::zeroed();
process_entry.dwSize = mem::size_of::<PROCESSENTRY32W>() as u32;
if Process32FirstW(snapshot, &mut process_entry) == TRUE {
loop {
res.push(ProcessInfo {
pid: process_entry.th32ProcessID as u64,
name: String::from_utf16_lossy(&process_entry.szExeFile)
.trim()
.to_string()
.replace("\0", ""),
});
// println!("Process ID: {}, Name: {}", process_entry.th32ProcessID, String::from_utf16_lossy(&process_entry.szExeFile));
if Process32NextW(snapshot, &mut process_entry) != TRUE {
break;
}
}
}
winapi::um::handleapi::CloseHandle(snapshot);
}
res
}
#[cfg(target_os = "windows")]
/// Attempts to terminate a process with the specified PID on a Windows system.
///
/// # Arguments
///
/// * `pid` - The process ID of the process to be terminated.
///
/// # Examples
///
/// ```
/// let pid_to_kill = 12345;
/// kill_process_by_pid(pid_to_kill);
/// ```
pub fn kill_process_by_pid(pid: u64) {
use winapi::shared::minwindef::{DWORD, FALSE};
use winapi::um::handleapi::CloseHandle;
use winapi::um::processthreadsapi::{OpenProcess, TerminateProcess};
use winapi::um::winnt::PROCESS_TERMINATE;
unsafe {
let process_handle = OpenProcess(PROCESS_TERMINATE, FALSE, pid as DWORD);
if process_handle.is_null() {
eprintln!("Failed to open process with PID: {}", pid);
return;
}
if TerminateProcess(process_handle, 0) == FALSE {
eprintln!("Failed to terminate process with PID: {}", pid);
}
CloseHandle(process_handle);
}
}
}
#[cfg(feature = "process")]
pub use process::*;