如何检查文件是否已在C中打开

use*_*403 9 c linux

我正在研究一个多线程系统,根据文件访问权限,可以在不同的线程之间共享文件.如何检查文件是否已被另一个线程打开.提前致谢

dca*_*ell 2

您可以使用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

这里有更多关于集群及其潜在弱点的信息。