命令panic,进程无法访问正在使用的文件



我试图通过Comand::new在我的Rust代码中生成CLI。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);

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

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");

最新更新