Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

File write just before exit seems racey #306

Closed
ThinkChaos opened this issue Apr 27, 2024 · 2 comments
Closed

File write just before exit seems racey #306

ThinkChaos opened this issue Apr 27, 2024 · 2 comments

Comments

@ThinkChaos
Copy link

Hi,

I've got an issue with data written to a file right before exiting is lost.
It seems it's a race condition somewhere because, with a lot of tries the data can show up, and adding a small delay solves it consistently.
I'm creating the issue in this repo because I'm not sure which part of the stack is the issue.

Here's a minimal repro (see below for a full crate):

use smol::io::AsyncWriteExt;

fn main() {
    smol::block_on(write_file());
}

async fn write_file() {
    let data = b"Now you see me";
    let mut file = smol::fs::File::create("now-you-dont.txt").await.unwrap();

    file.write_all(data).await.unwrap();
}

Something that seems interesting is that if I use write instead of write_all and output the number of written bytes, it's 14 as expected. Outputting that number using a print adds enough delay for the data to be written, but using the process exit code I get the right number and an empty file.

Here's a repo with a full crate so that all dependencies are pinned: smol-bug-repro.
I tested this using all combinations of:

  • rustc
    • 1.76.0 (07dca489a 2024-02-04) (built from a source tarball)
    • 1.77.1 (7cf61ebde 2024-03-27) (built from a source tarball)
  • smol
    • 1.3.0
    • 2.0.0

Hopefully you can reproduce, otherwise let me know what I can do to help.

@taiki-e
Copy link
Collaborator

taiki-e commented Apr 28, 2024

This is the intended behavior and is due to the limitations of async rust.

Please read the documentation: https://docs.rs/smol/latest/smol/fs/struct.File.html

NOTE: If writing to a file, make sure to call flush(), sync_data(), or sync_all() before dropping the file or else some written data might get lost!

@ThinkChaos
Copy link
Author

Ah right async drop gotcha. Thanks for the quick reply!

@ThinkChaos ThinkChaos closed this as not planned Won't fix, can't repro, duplicate, stale Apr 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants