How find out which process is using a file in Linux?

LinuxPs

Linux Problem Overview


I tried to remove a file in Linux using rm -rf file_name, but got the error:

rm: file_name not removed.  Text file busy

How can I find out which process is using this file?

Linux Solutions


Solution 1 - Linux

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

Solution 2 - Linux

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

Solution 3 - Linux

For users without fuser :

Although we can use lsof, there is another way i.e., we can query the /proc filesystem itself which lists all open files by all process.

# ls -l /proc/*/fd/* | grep filename

Sample output below:

l-wx------. 1 root root 64 Aug 15 02:56 /proc/5026/fd/4 -> /var/log/filename.log

From the output, one can use the process id in utility like ps to find program name

Solution 4 - Linux

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkhrisView Question on Stackoverflow
Solution 1 - Linuxjimm-clView Answer on Stackoverflow
Solution 2 - LinuxghotiView Answer on Stackoverflow
Solution 3 - LinuxManickarajView Answer on Stackoverflow
Solution 4 - LinuxMadinabonu AlisherovaView Answer on Stackoverflow