やりたいこと
下記のラッパーAPIの CreateProcessW を使い、プロセス(calc.exe)を起動することです。
RustのMicrosoft公式のWindows APIラッパーを使っています。
URL:https://github.com/microsoft/windows-rs
数回に1回程度起動しますが、大抵の場合失敗し、エラーコード(GetLastErrorで取得したもの)が
2(指定されたファイルが見つかりません。)と出てしまいます。
確実に存在するプログラム名・パスのはずなのに、数回に1回しか起動せず、しかも起動しない「理由が指定されたパスがない」と言う内容です。(もちろん、"C:\\Windows\\System32\\calc.exe"
と絶対パス表記にしても同様の確率で失敗します。)
以下コードのどこに問題点ありそうでしょうか。
開発環境
OS: Windows 10 21H1 build 19043.1586
Rustツールチェイン:stable-x86_64-pc-windows-gnu (default)
Rustコンパイラ:rustc 1.59.0 (9d1b2106e 2022-02-23)
Cargo:cargo 1.59.0 (49d8809dc 2022-02-10)
コード(設定ファイル)
cargo.toml
1[package] 2name = "test" 3version = "0.1.0" 4edition = "2021" 5 6# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 8[dependencies] 9 10[dependencies.windows] 11version = "0.34.0" 12features = [ 13 "alloc", 14 "Data_Xml_Dom", 15 "Win32_Foundation", 16 "Win32_Security", 17 "Win32_System_Threading", 18 "Win32_UI_WindowsAndMessaging", 19 "Win32_Storage_FileSystem" 20] 21 22[dependencies.windows-sys] 23version = "0.34.0" 24features = [ 25 "Win32_Foundation", 26 "Win32_System_Diagnostics_Debug", 27 "Win32_Security", 28 "Win32_System_Threading", 29 "Win32_UI_WindowsAndMessaging", 30 "Win32_System_Kernel" 31] 32 33[profile.release] 34opt-level = "z" # Optimize for size. 35lto = true 36codegen-units = 1 37panic = "abort"
コード本体
main.rs
1pub(crate) fn main() { 2 unsafe { 3 process_test("calc.exe"); 4 } 5} 6 7use std::{ 8 ffi::{CString, OsStr, OsString}, 9 mem::size_of, 10 os::windows::prelude::OsStrExt, 11 ptr::{null, null_mut}, 12}; 13 14use windows::{ 15 core::{PCWSTR, PWSTR}, 16 Win32::{Foundation::*, Security, Storage::FileSystem::*, System::Threading::*}, 17}; 18 19use std::mem::zeroed; 20unsafe fn process_test(process: impl Into<String>) { 21 let mut process = HANDLE::default(); 22 let process = process.into(); 23 process = create_process(process.clone()); 24} 25 26unsafe fn create_process(command_line: String) -> HANDLE { 27 let mut start_info = zeroed::<STARTUPINFOW>(); 28 start_info.cb = size_of::<STARTUPINFOW>() as u32; 29 let mut proc_info = zeroed::<PROCESS_INFORMATION>(); 30 println!("command line: {}", command_line); 31 let command_line= PWSTR( 32 OsString::from(&command_line) 33 .encode_wide() 34 .collect::<Vec<u16>>() 35 .as_mut_ptr(), 36 ); 37 let err = CreateProcessW( 38 null(), 39 command_line, 40 null(), 41 null(), 42 false, 43 CREATE_SUSPENDED, // この状態で起動するとWindowは出ないがタスクマネージャでは確認できる 44 null(), 45 PCWSTR::default(), 46 &mut start_info, 47 &mut proc_info, 48 ); 49 if err == false { 50 println!("{:?}", GetLastError()); 51 } 52}
上記以外になにか不明点有りましたら追記いたしますので、何卒ご回答宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー