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

后端 未结 10 1793
耶瑟儿~
耶瑟儿~ 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.

    0 讨论(0)
  • 2020-12-02 02:32

    As @Neil Butterworth says, the standard library doesnt.

    In unix you can use fcntl to use file locks.

    You could write a wrapper for your open function, that checks for a lock (and locks if none exists) a file if its open by no one else. You shold write a wrapper for close as well, that releases that lock on file close.

    0 讨论(0)
  • 2020-12-02 02:33

    There's a command-line too and API that have been added to the Linux kernel and do just that: inotify.

    Here's the man page.

    0 讨论(0)
  • 2020-12-02 02:39

    Non-natively, you could call out to Sysinternals' handle.exe as a last resort...

    0 讨论(0)
提交回复
热议问题