进程的命令恐慌无法访问已在使用的文件
Command panics with process cannot access the file already being used
我正在尝试通过 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
。解决此问题的最简单方法是 drop(file);
prior to 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");
我正在尝试通过 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
。解决此问题的最简单方法是 drop(file);
prior to 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");