flock会在进程退出时自动释放吗?

时间:2012-06-11 21:13:08

标签: linux bash unix operating-system

在Linux中的bash脚本中,我使用flock [命令flock,而不是系统调用flock()]来实现文件锁定,从而防止对共享资源(这是tmpfs中的文件)的并发访问。

我有陷阱处理程序来处理我脚本的异常终止: trap "{ rm -rf $LOCK ; rm -rf $TMPFS_FILE; exit 255; }" SIGINT SIGTERM

其中$ LOCK是我的锁文件,$ TMPFS_FILE是我的共享资源。

我的问题是我是否需要明确地执行文件解锁?或者Linux在所有程序终止[自愿终止和强制]情况下都会为我做这件事吗?

1 个答案:

答案 0 :(得分:16)

来自man 1 flock

  

-u, - unlock

          Drop  a  lock.   This  is  usually not required, since a lock is
          automatically dropped when the file is closed.  However, it  may
          be  required  in special cases, for example if the enclosed com‐
          mand group may have forked a background process which should not
          be holding the lock.