如何通过Linux shell命令关闭文件描述符
/proc/pid/fd/
中,文件描述符过多。我可以使用 shell 命令关闭这些文件描述符吗?
In /proc/pid/fd/
, there are too many file descriptors. Can I use shell command to close these file descriptors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只要您有权限,您绝对可以关闭其他正在运行的进程的 fd。
首先,找到PID。
然后,启动 gdb 并附加到进程:
然后,对要关闭的 fd 调用 close 系统调用:
如果文件描述符是泄漏的,那么程序将永远不会尝试再次使用它,而且它应该'不会引起任何问题。然而,该程序很可能有一个错误。
You can definitely close fd's of other running processes as long as you have the permissions to do so.
First, find the PID.
Then, start gdb and attach to the process:
Then, call the close system call on the fd you want to close:
If the file descriptor was a leaked one, then the program will never try to use it again anyway, and it shouldn't cause any issues. The program most likely has a bug, however.
您可以在 bash 中关闭当前进程的 FD
n
,如下所示:You can close a FD
n
of the current process in bash as so:@Thomas 答案仅在安装
close()
调用的调试信息时才有效。如果没有安装调试信息,gdb 拒绝调用
close()
:在这种情况下,让 gdb 调用
close()
最简单的方法是将调用强制转换为close ()
返回类型:请参阅 gdb 文档:
@Thomas answer is valid only when debug information for
close()
call is installed.Without debug info installed, gdb refuses to call
close()
:The simplest way to make gdb call
close()
in this case is to cast the call toclose()
return type:See gdb documentation:
我也遇到过类似的情况,但 gdb 不是一个选项,因为它破坏了我的应用程序的实时约束并扭曲了我的测试。
所以我想出了一个快速的 iptables 规则。 将可选参数放入方括号中 (
[ opt ]
)。查找您的目的地地址和端口:
netstat --program [ --numeric-host --numeric-ports ] |
netstat --program [ --numeric-host --numeric-ports ] | grep []/[]
在这里,我想剪切
10.56.4.79:57000
。创建
iptables
规则来切断套接字:iptables -A OUTPUT [ --out-interface; --协议] --destination <地址> --dport <端口> --jump DROP
在此阶段,您的程序无法向远程主机发送数据包。在大多数情况下,TCP 连接已关闭。如果有的话,您可以继续进行测试。
删除
iptables
规则:您只需输入相同的
iptables
规则,将A
替换为D
。I've ran in a similar situation, but where
gdb
was not an option since it disrupted the real-time constraints of my application and distorted my test.So I came up with a quick
iptables
rule. Optional arguments put into square brackets ([ opt ]
).Find your destination address and port:
netstat --program [ --numeric-host --numeric-ports ] | grep [<pid>]/[<appname>]
Here, I'd like to cut
10.56.4.79:57000
.Create an
iptables
rule to cut the socket:iptables -A OUTPUT [ --out-interface <if> --protocol <tcp|udp|unix> ] --destination <addr> --dport <port> --jump DROP
At this stage, your program can't send packets to the distant host. In most cases, the TCP connection is closed. You can proceed with your tests if there is some.
Remove the
iptables
rule:You just type in the same
iptables
rule replacing theA
by aD
.您不能只是关闭其他进程的文件描述符并期望它们继续工作。
修复打开文件过多的程序,使其打开的文件较少。这可能是配置更改,或修改源等。您不能只是关闭它的文件。
You can't just go around closing other processes' file descriptors and expect them to keep working.
Fix the program which has too many files open to make it open fewer. This may be a config change, or modifying the source etc. You can't just close the files for it.