it编程 > 编程语言 > rust

Rust调用Windows API 如何获取正在运行的全部进程信息

152人参与 2024-11-19 rust

前言

windows api官方文档 提供了c++的调用示例,最近想尝试用rust去实现,本系列博客记录一下实现过程。

依赖

rust调用windows api需要引入依赖winapi,在cargo.toml中添加依赖

winapi = "0.3.9"

调用不同的api集就需要使用相应的功能features,很好的一个判断方式是你在微软官方文档中看到的是在哪个头文件内,就添加哪个feature,例如本篇文章需要使用 tlhelp32.h processthreadsapi.h 那么就将这俩feature添加进去

winapi = { version = "0.3.9", features = ["tlhelp32", "processthreadsapi"] }

实现

大致步骤

创建快照句柄

创建进程快照需要用到 createtoolhelp32snapshot 方法,它在 tlhelp32.h 头文件中定义。

use winapi::um::tlhelp32::{createtoolhelp32snapshot, th32cs_snapprocess};
use winapi::um::handleapi::invalid_handle_value;
use winapi::um::errhandlingapi::getlasterror;
/// 保存进程快照并返回进程信息迭代器 `processinformationiterator`
pub fn list() -> result<processinformationiterator, string> {
    let process_snapshot: handle = unsafe { createtoolhelp32snapshot(th32cs_snapprocess, 0) };
    if process_snapshot == invalid_handle_value || process_snapshot.is_null() {
        unsafe {
            return err(format!("cannot list processes, code: {}", getlasterror()));
        }
    }
    ok(processinformationiterator::new(process_snapshot))
}

代码中的 processinfomationiterator 是自定义的,为了结构更清晰,这里使用迭代器模式来读取。

如果保存进程快照失败,返回的句柄会是一个无效的值(这里用了两个条件或的关系去判断是否无效,其实任用其一都可以,他们都表示一个“空”内存或“空”指针),使用 getlasterror 方法可以获取错误代码,错误代码对应含义见系统错误代码说明,也可以通过api解析成可读文本,这个后面的文章再介绍,这里先用code简单表示一下。

实现迭代器

rust中的迭代器模式实现方法这里就不多赘述,你只需要知道实现一个迭代器至少需要 一个迭代元素item一个实现了iterator特征的迭代器 就可以了。

迭代元素item

let vec = vec![1, 2]
for item in vec {
	...
}

上面代码的item就是迭代器中具体的元素,因为进程信息有很多,这里就使用一个结构体来存

use winapi::um::tlhelp32::processentry32;
pub struct processinformation {
    inner: processentry32,
}

这里并没有直接将进程的数据解析之后再存入结构体,而是直接将 processentry32 结构体做一个包装,这里是为了节省不必要的计算,从句柄中直接读取出来的 processentry32 并不是所有信息都是rust直接可读的,在需要时才解析,并且通过getter方法读取数据更方便以后拓展,下面是processinformation的具体方法实现。

use winapi::um::processthreadsapi::{getpriorityclass, openprocess};
use winapi::um::errhandlingapi::getlasterror;
use winapi::um::tlhelp32::processentry32;
use winapi::um::winnt::{handle, process_all_access};
pub(crate) fn char_arr_to_string(chars: &[i8]) -> string {
    chars.into_iter().map(|&c| c as u8 as char).collect()
}
impl processinformation {
    pub(crate) fn new(entry: processentry32) -> processinformation {
        processinformation {
            inner: entry
        }
    }
    /// 获取进程id
    pub fn get_pid(&self) -> u32 {
        self.inner.th32processid as u32
    }
    /// 获取进程名
    pub fn get_name(&self) -> string {
        char_arr_to_string(&self.inner.szexefile)
    }
    /// 获取父进程id
    pub fn get_parent_pid(&self) -> u32 {
        self.inner.th32parentprocessid as u32
    }
    /// 获取线程数量
    pub fn get_thread_count(&self) -> usize {
        self.inner.cntthreads as usize
    }
    /// 获取基础优先权值
    pub fn get_priority_base(&self) -> i64 {
        self.inner.pcpriclassbase as i64
    }
    /// 获取优先权类别,如果调用进程没有指定权限可能会获取失败,失败时返回 `none`
    pub fn get_priority_class(&self) -> option<i32> {
        let mut priority_class = none;
        unsafe {
            let handle = openprocess(process_all_access, 0, self.inner.th32processid);
            if !handle.is_null() {
                let class = getpriorityclass(handle);
                closehandle(handle);
                priority_class = some(class as i32);
            }
        }
        priority_class
    }
}

迭代器实现

迭代器中需要保存一些迭代遍历的状态,因此除了前面保存的快照句柄之外还要存储迭代的索引以及释放句柄的状态,迭代器是不可逆的

use winapi::um::winnt::handle;
pub struct processinformationiterator {
    process_snapshot: handle,
    index: usize,
    finished: bool,
}
impl processinformationiterator {
    pub(crate) fn new(process_snapshot: handle) -> processinformationiterator {
        processinformationiterator {
            process_snapshot,
            index: 0,
            finished: false,
        }
    }
}

然后就是迭代器的具体实现

use winapi::um::winnt::handle;
use winapi::um::tlhelp32::{process32first, process32next, processentry32};
use winapi::um::handleapi::closehandle;
impl iterator for processinformationiterator {
    type item = processinformation;
    fn next(&mut self) -> option<self::item> {
        if self.finished {
            return none;
        }
        self.index += 1;
        let mut entry: processentry32 = unsafe { std::mem::zeroed() };
        entry.dwsize = size_of::<processentry32>() as u32;
        //  读取快照中的第一个进程
        let res = unsafe {
            if self.index == 1 {
                process32first(self.process_snapshot, &mut entry)
            } else {
                process32next(self.process_snapshot, &mut entry)
            }
        };
        if res == 0 {
            unsafe {
                closehandle(self.process_snapshot);
            }
            self.finished = true;
            return none;
        }
        some(processinformation::new(entry))
    }
}

上面的代码有几点需要说明一下:

特殊情况处理:如果用户并没有迭代完,上面的代码实现可能会出现快照句柄未释放的情况,所以还需要给迭代器实现一个drop特征,在释放迭代器时释放快照句柄

impl drop for processinformationiterator {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        // 释放快照句柄。
        unsafe {
            closehandle(self.process_snapshot);
        }
        self.finished = true;
    }
}

代码汇总

我在写的时候放在了自定义的utils::process::win包下面,具体引用路径根据自己的情况调整

mod.rs文件

use crate::utils::process::win::process_information::processinformationiterator;
use winapi::um::tlhelp32::{createtoolhelp32snapshot, th32cs_snapprocess};
use winapi::um::errhandlingapi::getlasterror;
use winapi::um::handleapi::invalid_handle_value;
use winapi::um::winnt::handle;
pub mod process_information;
pub fn list() -> result<processinformationiterator, string> {
    let process_snapshot: handle = unsafe { createtoolhelp32snapshot(th32cs_snapprocess, 0) };
    if process_snapshot == invalid_handle_value || process_snapshot.is_null() {
        unsafe {
            return err(format!("cannot list processes, code: {}", getlasterror()));
        }
    }
    ok(processinformationiterator::new(process_snapshot))
}
pub(crate) fn char_arr_to_string(chars: &[i8]) -> string {
    chars.into_iter().map(|&c| c as u8 as char).collect()
}

process_information.rs文件

use crate::utils::process::win::char_arr_to_string;
use crate::utils::process::win::process_module::processmoduleiterator;
use winapi::um::errhandlingapi::getlasterror;
use winapi::um::handleapi::closehandle;
use winapi::um::processthreadsapi::{getpriorityclass, openprocess};
use winapi::um::tlhelp32::{process32first, process32next, processentry32};
use winapi::um::winnt::{handle, process_all_access};
/// [processentry32](https://learn.microsoft.com/zh-cn/windows/win32/api/tlhelp32/ns-tlhelp32-processentry32) 的rust包装实现
pub struct processinformation {
    inner: processentry32,
}
impl processinformation {
    pub(crate) fn new(entry: processentry32) -> processinformation {
        processinformation {
            inner: entry
        }
    }
    /// 获取进程id
    pub fn get_pid(&self) -> u32 {
        self.inner.th32processid as u32
    }
    /// 获取进程名
    pub fn get_name(&self) -> string {
        char_arr_to_string(&self.inner.szexefile)
    }
    /// 获取父进程id
    pub fn get_parent_pid(&self) -> u32 {
        self.inner.th32parentprocessid as u32
    }
    /// 获取线程数量
    pub fn get_thread_count(&self) -> usize {
        self.inner.cntthreads as usize
    }
    /// 获取基础优先权值
    pub fn get_priority_base(&self) -> i64 {
        self.inner.pcpriclassbase as i64
    }
    /// 获取优先权类别,如果调用进程没有指定权限可能会获取失败,失败时返回 `none`
    pub fn get_priority_class(&self) -> option<i32> {
        let mut priority_class = none;
        unsafe {
            let handle = openprocess(process_all_access, 0, self.inner.th32processid);
            if !handle.is_null() {
                let class = getpriorityclass(handle);
                closehandle(handle);
                priority_class = some(class as i32);
            }
        }
        priority_class
    }
}
pub struct processinformationiterator {
    process_snapshot: handle,
    index: usize,
    finished: bool,
}
impl processinformationiterator {
    pub(crate) fn new(process_snapshot: handle) -> processinformationiterator {
        processinformationiterator {
            process_snapshot,
            index: 0,
            finished: false,
        }
    }
}
impl drop for processinformationiterator {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        // 释放快照句柄。
        unsafe {
            closehandle(self.process_snapshot);
        }
        self.finished = true;
    }
}
impl iterator for processinformationiterator {
    type item = processinformation;
    fn next(&mut self) -> option<self::item> {
        if self.finished {
            return none;
        }
        self.index += 1;
        let mut entry: processentry32 = unsafe { std::mem::zeroed() };
        entry.dwsize = size_of::<processentry32>() as u32;
        //  读取快照中的第一个进程
        let res = unsafe {
            if self.index == 1 {
                process32first(self.process_snapshot, &mut entry)
            } else {
                process32next(self.process_snapshot, &mut entry)
            }
        };
        if res == 0 {
            unsafe {
                closehandle(self.process_snapshot);
            }
            self.finished = true;
            return none;
        }
        some(processinformation::new(entry))
    }
}

测试

测试代码

#[test]
pub fn test_list() {
    println!("pid\tname\tparent pid\tthreads\tpriority base\tpriority class");
    let iter = list().unwrap();
    for process in iter {
        let pid = process.get_pid();
        let name = process.get_name();
        let parent_pid = process.get_parent_pid();
        let thread_count = process.get_thread_count();
        let priority_base = process.get_priority_base();
        let priority_class = process.get_priority_class();
        println!("{}\t{}\t{}\t{}\t{}\t{:?}", pid, name, parent_pid, thread_count, priority_base, priority_class)
    }
}

结果

pid     name    parent pid      threads priority base   priority class
0       [system process]        0       6       0       none
4       system  0       236     8       none
64      secure system   4       0       8       none
132     registry        4       4       8       none
504     smss.exe        4       2       11      none
728     csrss.exe       712     11      13      none
824     wininit.exe     712     1       13      none
832     csrss.exe       816     15      13      none
...
12624   chrome.exe      12148   19      8       some(32)
16352   chrome.exe      12148   18      4       some(64)
14904   chrome.exe      12148   17      4       some(64)
14672   wslinstaller.exe        892     2       8       none
11160   chrome.exe      12148   20      4       some(64)
18048   chrome.exe      12148   19      4       some(64)
5452    chrome.exe      12148   14      4       some(64)
14468   svchost.exe     892     3       8       none
18060   chrome.exe      12148   14      4       some(64)
17748   dllhost.exe     688     8       8       some(32)
16084   vctip.exe       16648   27      8       some(32)
9008    openconsole.exe 10644   6       8       some(32)
15516   cargo.exe       10644   4       8       some(32)
11312   cargo.exe       15516   4       8       some(32)

到此这篇关于rust调用windows api 获取正在运行的全部进程信息的文章就介绍到这了,更多相关rust调用windows api 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Rust整合Elasticsearch的详细过程(收藏)

11-02

如何使用宝塔部署RustDesk中继服务器

12-17

解决Ubuntu“E:Unable to locate package“错误问题

12-17

Rust中自定义Debug调试输出的示例详解

12-19

Rust的slab库使用场景分析

12-22

rust的nutyp验证和validator验证数据的方法示例详解

09-29

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论