C get all open file descriptors

Deadly 提交于 2019-12-30 09:32:12

问题


I want to implement behavior in my C program so that if a SIGINT happens, I close all open file descriptors. Is there a simple way to get a list of them?


回答1:


I'd use brute force: for (i = 0; i < fd_max; ++i) close (i);. Quick and pretty portable.




回答2:


Keep track of all of your open file descriptors and close them individually.

In the general case, a library you're using might have an open file, and closing it will cause that library to misbehave.

In fact, the same problem could exist in your own code, because if you close file descriptors indiscriminately but another part of your program still remembers the file descriptor and tries to use it, it will get an unexpected error or (if other files have been opened since) operate on the wrong file. It is much better for the component responsible for opening a file to also be responsible for closing it.




回答3:


You could read out the content of /proc/<pid>/fd., if available.

But be aware of the potiential race, that might occur if your application closes some or opens new ones in between your read out /proc/<pid>/fd and you are going to close what you read.

So conculding I want to recommend Kevin Reid's approach to this.




回答4:


My solution for POSIX systems:

All opened fd's are the lowest value possible.
Make a wrapper function upon open(2).
Your new function open (and return) the requested fd and pass his value to a function called define_if_is_the_higtest_fd_and_store_it().
You should have a int hightest_fd_saved accessible only for a singleton function (there is only 1 'descriptor table') named save_fd() (initial value is 3 (cuz stderr is 2)).
Configure SIGINT to your signal function. Inside, you do a loop from [3, return_fd()].

I think that's it...



来源:https://stackoverflow.com/questions/13101690/c-get-all-open-file-descriptors

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