为了防止重复的应用程序实例运行,我使用
CreateMutexA
Win32 API 调用创建互斥体。但是,这并不能防止重复进程,因为会创建多个具有相同名称的互斥体。我做错了什么?
代码:
use windows::Win32::Foundation::{
GetLastError,
ERROR_ALREADY_EXISTS
};
use windows::Win32::System::Threading::{
CreateMutexA,
};
use windows::core::PCSTR;
pub fn prevent_duplicate() {
let mutex_key = static_key_as_string!();
log::info!("Mutex value: {mutex_key}");
log::info!("Creating Mutex");
unsafe {
match CreateMutexA(None, false, PCSTR(mutex_key.as_ptr() as *const u8)) {
Ok(_) => {
let error = GetLastError();
log::error!("{:?} {:?}", error, ERROR_ALREADY_EXISTS);
if error == ERROR_ALREADY_EXISTS {
log::info!("Mutex exists. Exiting");
std::process::exit(0)
}
},
Err(_) => {
log::error!("Could not check existence of Mutext. Continuing");
},
};
}
}
输出过程1:
[INFO ] Mutex value: P889Z0Hhy2TKEPykDSLuSWdE9bJfNfCsK87aqgNGZ6b09NBIwBh6bwJBj98AkTzO
[INFO ] Creating Mutex
[ERROR] WIN32_ERROR(0) WIN32_ERROR(183)
输出过程2:
[INFO ] Mutex value: P889Z0Hhy2TKEPykDSLuSWdE9bJfNfCsK87aqgNGZ6b09NBIwBh6bwJBj98AkTzO
[INFO ] Creating Mutex
[ERROR] WIN32_ERROR(0) WIN32_ERROR(183)
编辑:将
bInitialOwner
设置为 true
仍然允许多个实例