【问题标题】:rust File::create() sometimes returns os error 32rust File::create() 有时会返回操作系统错误 32
【发布时间】:2020-07-22 22:59:13
【问题描述】:

所以我有一个看起来像这样的函数:

fn write_file(path: &PathBuf, data: Vec<u8>) -> Result<i32,std::io::Error>{
    let mut buffer = File::create(path)?;
    buffer.write_all(&data)?;
    buffer.flush()?;
    Ok(0)
}

它每秒循环运行大约 10 次,接收 Vec&lt;u8&gt; 并重复将其写入同一文件 tmp.exe。当我运行该程序时,它可以完美运行数百个循环,但最终File::create()The process cannot access the file because it is being used by another process. (os error 32) 发生恐慌。

起初我认为这可能与我在写入之间运行文件有关(即使我在继续之前等待退出代码)。所以我尝试不运行它,而只写入文件,但我仍然遇到同样的错误。由于我在 Windows 上,我还尝试关闭我的 AV,以为它可能正在对新写入的文件进行某种检查,但这也没有解决它。知道这里发生了什么吗?

更新:我已设法将问题隔离为:

use std::path::PathBuf;
use std::fs::File;
use std::io::prelude::*;

fn write_file(path: &PathBuf, data: Vec<u8>) {
    let mut buffer = File::create(path).unwrap(); //error happens here
    buffer.write_all(&data).unwrap();
    buffer.flush().unwrap();
}

fn main() {
    let mut i = 0;
    loop {
        write_file(&PathBuf::from(r"tmp.exe"), vec!(0x90, 0x90, 0x90, 0x90));
        i+=1;
        println!("{}",i);
    }
}

返回

2894
2895
2896
2897
2898
2899
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 32, kind: Other, message: "The process cannot access the file because it is being used by another process." }', src\main.rs:6:22
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\playground.exe` (exit code: 101)

【问题讨论】:

  • 在 Procmon 中查看与 tmp.exe 相关的调用可能会很有趣。
  • 我在其他语言中看到了同样的行为,在选定的 Windows 机器上,同样的代码在其他机器上也能完美运行。我仍然认为它与杀毒软件有关......

标签: windows file rust


【解决方案1】:

好吧,我找到了一个解决方案,虽然我不确定它是否是最好的解决方案,考虑到如果文件实际上很忙,它可能会导致无限循环。如果遇到 Os Error 32,我将其设置为简单地重试

fn write_file(path: &PathBuf, data: Vec<u8>) -> Result<i32,std::io::Error>{
    let mut buffer: File = loop {
        match File::create(path) {
            Ok(file) => break file,
            Err(e) => match e.raw_os_error() {
                Some(32) => continue,
                _ => return Err(e)
            } 
        };
    };
    buffer.write_all(&data)?;
    buffer.flush()?;
    Ok(0)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2021-05-21
    相关资源
    最近更新 更多