Check if a file is open in another process
Is there any way to open a file with non-sharing exclusive read-write access?
A file change event from fs.watch
does not necessarily mean that the file has been completely written, In the case of most node based processes more chunks are coming down the stream, or it might just not have been flushed yet.
fs.open
lets a file that is already open and being streamed to be opened, in write mode without an error. One could introduce a timeout delay but that's just too brittle and arbitrary.
On windows, one would be able to do CreateFile
with FILE_SHARE_NONE
from C, can't quite recall what the equivalent is on Linux (as locks are advisory if i remember correctly), don't know if OS X has an equivalent, posix or otherwise).
You can use @ronomon/opened to check if a file is open in another process, if any applications have open handles or file descriptors to the file.
It won't tell you which applications have the file open, only that the file is open in other applications.
It works on Windows, macOS and Linux and requires privileges only on Linux.
It uses a native binding on Windows to open the file with exclusive sharing mode to detect any sharing violations due to other processes with open handles.
On macOS and Linux it wraps lsof
.
Compared to using an alternative such as flock
, as far as I understand, flock
is only advisory, so it will only work if all processes cooperate to check the lock, which is not the case most of the time if the processes are independent.
请参阅fs-ext
软件包中的flock
函数。
上一篇: Spring Data一对多映射
下一篇: 检查一个文件是否在另一个进程中打开