How to detect whether a file is being written by any other process in Linux?

How to detect whether a file is being written by any other process in Linux?

Before a program open a file to processes it, it wants to ensure no other processes are writing to it. Here, we are sure after the files are written and closed, they will not be written any more. Hence, one-time checking will be good enough.

You may not know whether the file is being written. However, you may use lsof to check whether the file is opened by any other processes. Programs like cp will close the file after the work is done. So you may bet on it for most situations.

For a file without any other process opening it:

$ lsof -f -- ~/.bashrc

With one process openning for reading:

$ lsof -f -- ~/.bashrc
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
less    14558  zma    4r   REG  253,3     1356 27787271 /home/zma/.bashrc

With one process openning for writing:

$ lsof -f -- ~/.bashrc
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
vim     14840  zma   10w   REG  253,3     1355 27787271 /home/zma/.bashrc

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *