首页 > 解决方案 > 进程的命令恐慌无法访问已被使用的文件

问题描述

我试图在我的 Rust 代码中通过Comand::new. CLI 文件正在从二进制文件中提取到 exe 文件,然后使用Command::new. 但它给出了'ERROR: Os { code: 32, kind: Other, message: "The process cannot access the file because it is being used by another process." }'错误。

let taskmgr_pid = get_pid_by_name("Taskmgr.exe");
let process_hide = asset::Asset::get("cli.exe").unwrap();

let file_path = "C:\\filepathhere\\cli.exe";

let mut file = File::create(file_path.to_string()).expect("Couldn't create file");
file.write_all(&process_hide);

let res = Command::new(file_path)
    .arg(taskmgr_pid.to_string())
    .output()
    .expect("ERROR");

println!("PID: {}", taskmgr_pid);
println!("{:?}", res);

标签: rustprocesscommandstd

解决方案


file这是因为您在执行命令之前没有关闭。解决问题的最简单方法是简单地drop(file);Command::new().

let mut file = File::create(file_path).expect("unable to create file");
file.write_all(&process_hide).expect("unable to write");

drop(file);

let res = Command::new(file_path)
    .arg(taskmgr_pid.to_string())
    .output()
    .expect("ERROR");

推荐阅读