Mac OS X equivalent of Linux flock(1) command

2020-05-21 09:20发布

Is there a flock command on Mac OS X that manages file lock?

http://linux.die.net/man/1/flock

8条回答
姐就是有狂的资本
2楼-- · 2020-05-21 09:25

Just for completeness sake, you can compile flock(2) for OSX with some minor changes, i have not run any tests, but basic functionality works.

You can get the source from ftp://ftp.kernel.org//pub/linux/utils/util-linux. You then need to replace some calls to string functions not available on OSX, and you're good to go.

Here: https://gist.github.com/Ahti/4962822 is my modified flock.c of version 2.22.1, you still need the other sources for headers though.

查看更多
在下西门庆
3楼-- · 2020-05-21 09:34

I don't believe that the flock command exists on OS X, but it does exist on BSD which should make it reasonably easy to port to OS X.

The closest that is available is the shlock command (man page), but it isn't as robust or secure as flock.

Your best bet may be to look at porting either the Linux or BSD version of flock to OS X.

查看更多
冷血范
4楼-- · 2020-05-21 09:34

Are you looking for flock the command line utility or flock the feature?

flock(1) is unavailable on OS X. flock(2) (the C function for file locking), however is.

Writing a simple command line flock(1) utility using flock(2) should be trivial.

查看更多
萌系小妹纸
5楼-- · 2020-05-21 09:35

There is no flock command on OS X, no. If you need a shell script that can share a lockable resource with programs that use the flock system call to manage access to that resource, you will have to create such a program - by compiling the BSD source yourself, or writing your own equivalent program (perhaps in Perl or Ruby or some other language that exposes flock as part of its high-level system interface).

If, however, all you need is a way to synchronize access to a file from a shellscript, and you don't have other programs already written trying to do so with flock, you could use the lockfile command, which comes with the procmail package. OS X used to ship with procmail; it no longer does, but you can install it via e.g. Homebrew.

查看更多
手持菜刀,她持情操
6楼-- · 2020-05-21 09:36

There is a cross-platform flock command here:

https://github.com/discoteq/flock

I have tested it and it works well on OSX as a drop-in replacement for the util-linux flock.

查看更多
何必那么认真
7楼-- · 2020-05-21 09:36

You cannot write a shell-level flock(1) command for use in shell programming because of how file locking working. The lock is on the descriptor, not on the inode or directory entry.

Therefore, if you implement a shell command that flocks something, as soon as the locking command exits and the shell script moves on to the next command, the descriptor that held the lock disappears and so there is no lock retained.

The only way to implement this would be as a shell builtin. Alternately, you have to rewrite in a programming language that actually supports flock(2) directly, such as Perl.

查看更多
登录 后发表回答