Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file is open in another process

Tags:

node.js

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).

like image 637
Casper Beyer Avatar asked Jul 01 '15 22:07

Casper Beyer


People also ask

How do you check if a file is open by another process in Java?

You can run from Java program the lsof Unix utility that tells you which process is using a file, then analyse its output.

How do you check if a file is opened by another program Python?

Any file is required to open before reading or write. The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated.


1 Answers

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.

like image 78
Joran Greef Avatar answered Sep 27 '22 16:09

Joran Greef