You can use the
fuser
command on Unix or Linux systems to determine
if any process has a file open or determine the specific process that has
the file open. The fuser
program is usually locate in /sbin,
so you will need to spcificy /sbin/fuser if it isn't in your path.
The output of the command may differ somewhat depending on the operating system
you are running. I've found that on a Solaris 7, Solaris 10, and SGI IRIX64
system that a command like fuser somefile.txt
will return the
filename followed by a colon and then the process ID (PID) of the process
that has the file open with a letter code indicating how the file is being used.
The letter code will be an "o", if the process is using the file as an open
file. Fuser will still return the filename followed by a colon
even if no process has the file open.
fuser somefile.txt
somefile.txt
However, on a Linux system, specifically a Redhat Linux 9 system, nothing is returned, if no process has the file open. You have to use a "-a" option if you want the same response as on the Unix systems mentioned above. If you use the "-a" option, you will see the filename followed by a colon and nothing else, but then you will also see "no process references; use -v for the complete list" on a line below.
$ /sbin/fuser -a somefile.txt
somefile.txt:
No process references; use -v for the complete list
I also don't see a letter code appended to the end of the PID when I run fuser on a Linux system and some process has the file open.
If you run fuser from a regular user account, you may get an indication
that no process has a file open when a process owned by another account
has the file open. E.g. I know that the /var/log/maillog file is open,
but checking it with fuser from a user account doesn't show that the
file is open. But, if I rerun fuser from the root account, I do see
which PID has the process open and can issue a ps -p
command followed by that PID to see the name of the process that has
the file open.
$ /sbin/fuser /var/log/maillog
$ /sbin/fuser -a /var/log/maillog
/var/log/maillog:
No process references; use -v for the complete list
$ su - root
Password:
# fuser /var/log/maillog
/var/log/maillog: 2599
# ps -p 2599
PID TTY TIME CMD
2599 ? 00:00:14 syslogd
You can kill a process that has a file open with the "-k" option, e.g.
fuser -k somefile.txt