dtc99987
2015-09-26 14:40
浏览 264

如何在GO中实现跨平台文件锁定

I need to implement the following behavior in GO:

  1. A process should be able to read a file irrespective if any other process has locked the file for writing
  2. A process should obtain a write lock, before it can write to the file. This is to ensure that multiple processes cannot write to the same file
  3. A process should not wait to obtain the write lock, if it cannot obtain a lock it should move on

For UNIX based systems, syscall package in GO defines flock function, which could be used to implement the above behaviour in the following manner:

  1. Use syscall.flock function with LOCK_EX | LOCK_NB to try and obtain a lock before writing to the file
  2. Do not check for any locks before reading from the file

syscall package for Windows in GO, does not include flock. Given this, how best can I write code that can execute cross-platform and has the behavior described above?

I want to try and achieve this without making OS specific calls or using unsafe.

PS: I do not want mandatory file locking, the processes will check for file lock before performing file operations

图片转代码服务由CSDN问答提供 功能建议

我需要在GO中实现以下行为:

    < li>一个进程应该能够读取文件,而不管是否有任何其他进程已锁定该文件以进行写入
  1. 一个进程应先获得写锁,然后才能写入文件。 这是为了确保多个进程无法写入同一文件
  2. 一个进程不应等待获取写锁,如果它无法获取应继续前进的锁 < / ol>

    对于基于UNIX的系统,GO中的syscall包定义了flock函数,该函数可以通过以下方式用于实现上述行为:

    1. 将syscall.flock函数与LOCK_EX一起使用| LOCK_NB尝试在写入文件之前获取锁
    2. 从文件读取前请勿检查任何锁

      syscall Windows中在GO中使用的软件包,不包括羊群。 鉴于此,我如何才能最好地编写可以执行跨平台并且具有上述行为的代码?

      我想尝试实现此目标而不用进行特定于操作系统的调用或使用不安全的方法。

      PS:我不希望强制文件锁定,该进程将在执行文件操作之前检查文件锁定

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douling1936 2017-07-31 09:37
    已采纳

    Use compiler flags.

    Flags for windows:

    // +build windows,!linux
    ...
    

    Flags for linux:

    // +build linux,!windows
    ...
    

    If you want to use platform native locking functions.

    A workaround might be to allocate resources which are (supposedly) singletons across platforms like binding to a port and relying on that being possible only once. The error condition of the bind operation will be the deciding factor.

    Personally I'd go with the option to use platform native options and just make an interface so that one can add tests easily and thereby make sure that things won't break.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题