1. Overview

In this article, we’ll see how to check if a file write is in progress in Linux. Knowing if a file writing operation is completed depends on each application. Thus, we’ll focus on two ways we can infer this – checking if the file is still open by a process and directly inspecting the file.

2. Is There a Process With the File Opened?

A writing operation may be in progress if any process has opened a certain file. However, even if a file is open, we still cannot be sure that the writing operation has been completed.

As a general guideline, if we’re concerned about the completion of a writing operation, it’s always better to use an advisory lock. If we can modify the program that’s writing the file, it’s better to have it state when the file writing operation is over.

2.1. lsof: Listing Open Files

We can use the utility lsof to know if there’s anything still using the file:

$ lsof -f -- sample_file
COMMAND   PID     USER   FD  TYPE  DEVICE SIZE/OFF     NODE NAME
less    61728 username   4r   REG     8,6        0  7347202 sample_file
less    61833 username   4r   REG     8,6        0  7347202 sample_file

We’ve used the -f — argument to restrict the search to those files whose name is exactly sample_file. The flag in this case may be overkill but if the file name is provided as a path **(containing /), the use of the flag is required.**

We can see that the file is in use twice by the less command. Moreover, we can know the file descriptor (4 in the output) and the mode (r for reading). If we see a w, it means that the process has opened the file to write it. If the file is being written, it has to be open with the file descriptor of w. However, if the file is not in use (and we get an empty output of lsof), we’ll get no information on why it’s no longer open.

Alternatively, we can get a similar output by considering all the files under a directory:

$ lsof +d directory/
COMMAND   PID     USER  FD TYPE DEVICE  SIZE/OFF     NODE NAME
bash    61044 username cwd  DIR    8,6      4096  7346869 directory
less    61442 username cwd  DIR    8,6      4096  7346869 directory
less    61442 username  4r  REG    8,6         0  7346873 directory/sample_file_1

Another major drawback of the lsof command is the way it knows a file is being used. lsof searches in the kernel memory for open files. Thus, rapid changes in kernel memory will most probably result in unpredictable results.

2.2. fuser: Which Processes Are Using a File