How to use lsof(List Opened Files) in a C/C++ application?

我们两清 提交于 2019-12-01 02:09:27

问题


Is there any way to get all opened sockets using c++? I know the lsof command and this is what I'm looking for, but how to use it in a c++ application?

The idea is to get the FD of an opened socket by its port number and the pid.


回答1:


Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc. No need to slog through the lsof sources. :)




回答2:


If you don't want to copy/paste or reimplement chunks of the lsof code, and it doesn't build any useful libraries you could leverage, you can still open a pipe to an lsof process and peruse its output.




回答3:


check the lsof source?

ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/




回答4:


The lsof command is prepared specifically such that it can be used from other programs including C, see the section: OUTPUT FOR OTHER PROGRAMS of man lsof for more information. For example you can invoke lsof with -F p and it will output the pid of the processes prefixed with 'p':

$ lsof -F p /some/file
p1234
p4321

you can then use popen to execute this commmand in a child process and read from its standard output.



来源:https://stackoverflow.com/questions/4470121/how-to-use-lsoflist-opened-files-in-a-c-c-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!