How to check if a file has been opened by another application in C++?

后端 未结 10 1824
耶瑟儿~
耶瑟儿~ 2020-12-02 01:55

I know, that there\'s the is_open() function in C++, but I want one program to check if a file hasn\'t been opened by another application. Is there any way to d

10条回答
  •  渐次进展
    2020-12-02 02:28

    If you control the other process (have source code), the best plan is to use advisory locks in both processes. This locking is defined in POSIX, and will be portable across operating systems.

    In Linux, you can use the utility lsof to see what files are opened by other processes.

    This is limited to what you have permissions for - you have to do the check as a privileged user, or you'll only get results for files opened by the same user as the one doing the check.

    I only know of the command line utility, not of any system call you can use directly from C code.

    In Linux, it's also possible to turn on mandatory locking for a given filesystem (mount -o mand), and set special flags on the file (chmod g-x,g+s). Then when your process attempts to acquire a write lock, it will fail if another process has the file open. This is hardly ever used, but if you completely control the system in question, it may be an option.

提交回复
热议问题