简体   繁体   English

如何找出哪个进程正在使用Linux中的文件?

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

I tried to remove a file in Linux using rm -rf file_name , but got the error:我尝试使用rm -rf file_name删除 Linux 中的文件,但出现错误:

rm: file_name not removed.  Text file busy

How can I find out which process is using this file?我怎样才能找出哪个进程正在使用这个文件?

You can use the fuser command, like:您可以使用fuser命令,例如:

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.您可以在fuser 的 Wikipedia 文章man页中找到更多信息。

@jim's answer is correct -- fuser is what you want. @jim 的回答是正确的—— fuser就是你想要的。

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.此外(或替代地),您可以使用lsof获取更多信息,包括用户名,以防您需要许可(无需运行其他命令)来终止进程。 (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.) (当然,如果您想要终止进程, fuser可以使用它的-k选项来做到这一点。您可以让fuser使用带有-s选项的其他信号——查看手册页了解详细信息。)

For example, with a tail -F /etc/passwd running in one window:例如,在一个窗口中运行tail -F /etc/passwd

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.请注意,您还可以使用lsof来找出哪些进程正在使用特定的套接字。 An excellent tool to have in your arsenal.您的武器库中的绝佳工具。

For users without fuser :对于没有fuser的用户:

Although we can use lsof , there is another way ie, we can query the /proc filesystem itself which lists all open files by all process.虽然我们可以使用lsof ,但还有另一种方法,即我们可以查询/proc文件系统本身,它列出了所有进程的所有打开文件。

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

Sample output below:样本output如下:

l-wx------. l-wx------。 1 root root 64 Aug 15 02:56 /proc/5026/fd/4 -> /var/log/filename.log 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从 output,可以使用ps等实用程序中的进程 ID 来查找程序名称

$ lsof | tree MyFold

As shown in the image attached:如附图所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM