hhvm / hsl-experimental

Experimental features for the Hack Standard Library
MIT License
23 stars 10 forks source link

Add function to truncate a file after it has been opened #165

Closed lexidor closed 2 years ago

lexidor commented 3 years ago

It is currently not possible to replace the contents of a file while holding an exclusive lock. File\open_write($path, File\WriteMode::TRUNCATE) truncates immediately, before you can create a lock.

This would make the following pattern possible. I don't think you can do this safely today.

$file = File\open_read_write('/some/file');
using ($file->tryLockx(File\LockType::SHARED)) {
  // Determine if action is required based on the file contents.
  $should_do_something = true;
}

if ($should_do_something) {
  using ($file->tryLockx(File\LockType::EXCLUSIVE)) {
    $old_bytes = await $file->readAllAsync();
    // Check if action is still required, since someone might
    // have written before you managed to get the exclusive lock.
    $file->truncate();
    await $file->writeAllAsync('new bytes');
  }
}
fredemmott commented 3 years ago

OS\ftruncate() should be added - _Private\_OS\ftruncate() already exists.

This should probably also be added to the FDHandle interface, but adding OS\ftruncate will be an easy first step with obvious design, and allow OS\ftruncate($handle->getFileDescriptor())