Skip to content

Windows: opening file in append mode breaks locking (?) #54118

@pkgw

Description

@pkgw

I think that std::fs has a bug in the interaction between the OpenOptions and file locking on Windows.

Consider the following test program, using the fs2 crate:

extern crate fs2;

use fs2::FileExt;
use std::fs;

fn main() {
    let f = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open("myfile.txt").expect("error creating");
    f.lock_exclusive().expect("error locking");
}

On Windows 10 this fails for me:

    Finished dev [unoptimized + debuginfo] target(s) in 0.99s                                                           
     Running `target\debug\examples\debug.exe`                                                                          
thread 'main' panicked at 'error locking: Os { code: 5, kind: PermissionDenied, message: "Access is denied." }', libcore
\result.rs:945:5                                                                                                        
note: Run with `RUST_BACKTRACE=1` for a backtrace.                                                                      
error: process didn't exit successfully: `target\debug\examples\debug.exe` (exit code: 101)   

If I use .write(true) instead of .append(true), it works fine.

I believe that what's happening here is that the append mode is setting too many flags. Here's the relevant code in the Windows FS implementation. Based on this MS doc page, my guess is that the Rust code is somehow interacting with the Windows SYNCHRONIZE flag in a way that's causing problems.

However, I'm not a native Windows dev so this isn't my area of expertise, and it's a bit tricky for me to investigate this in detail. But I can't find any evidence on the internet that the error above is an expected behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ioArea: `std::io`, `std::fs`, `std::net` and `std::path`O-windowsOperating system: WindowsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions