【发布时间】: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<u8> 并重复将其写入同一文件 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 机器上,同样的代码在其他机器上也能完美运行。我仍然认为它与杀毒软件有关......