您可以使用int fancy(int fd, int 操作); 将文件标记为锁定并检查它是否被锁定。
Apply or remove an advisory lock on the open file specified by fd.
The argument operation is one of the following:
LOCK_SH Place a shared lock. More than one process may hold a
shared lock for a given file at a given time.
LOCK_EX Place an exclusive lock. Only one process may hold an
exclusive lock for a given file at a given time.
LOCK_UN Remove an existing lock held by this process.
Run Code Online (Sandbox Code Playgroud)
如果您在每个线程中单独打开文件,flock应该在线程应用程序中工作: 多个线程能够同时获取flock
这里有更多关于集群及其潜在弱点的信息。