Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock a file for writing in Dart

Tags:

dart

I'd like to have two programs (running on different Dart VM) writing data to the same file (appending actually). However, I can't find lock or similar mechanism to avoid racing. Any suggestion? Thanks.

like image 983
Tom Yeh Avatar asked Feb 21 '14 02:02

Tom Yeh


1 Answers

File locking was just added. (http://dartbug.com/17045 was changed to fixed)

Copied example form https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tests/standalone/io/file_lock_script.dart?spec=svn42733&r=42733

import "dart:io";

main(List<String> args) {
  File file = new File(args[0]);
  int start = null;
  int end = null;
  var  mode = FileLock.EXCLUSIVE;
  if (args[1] == 'SHARED') {
    mode = FileLock.SHARED;
  }
  if (args[2] != 'null') {
    start = int.parse(args[2]);
  }
  if (args[3] != 'null') {
    end = int.parse(args[3]);
  }
  var raf = file.openSync(mode: WRITE);
  try {
    raf.lockSync(mode, start, end);
    print('LOCK SUCCEEDED');
  } catch (e) {
    print('LOCK FAILED');
  } finally {
    raf.closeSync();
  }
}

See also https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tests/standalone/io/file_lock_test.dart?spec=svn42733&r=42733 for a more extensive example.

like image 62
Günter Zöchbauer Avatar answered Oct 14 '22 21:10

Günter Zöchbauer