【问题标题】:Command panics with process cannot access the file already being used进程的命令恐慌无法访问已被使用的文件
【发布时间】:2021-01-17 13:52:49
【问题描述】:

我正在尝试通过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);

【问题讨论】:

    标签: rust process command std


    【解决方案1】:

    这是因为您在执行命令之前没有关闭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");
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2021-07-11
      • 2019-03-10
      • 1970-01-01
      • 2012-02-19
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多