26

もちろん、ほとんどの状況に対する即時の答えは「はい」です。私は、プロセスが割り当てられたリソースを正しくクリーンアップする必要があると固く信じていますが、私の状況では、固定された起動時にファイル記述子の数を取得し、終了する前にそれらをすべて閉じます。

これは組み込みプラットフォームであり、悪いスタイルを導入することなく、コードをできるだけコンパクトにしようとしています。しかし、とにかくファイル記述子は終了する前に閉じられるため、このファイル記述子のクリーンアップ コードは何らかの目的に役立ちますか? いつもすべてのファイル記述子を閉じていますか?

4

5 に答える 5

13

使い終わったらファイル記述子を閉じると、コードが再利用しやすくなり、拡張しやすくなります。これは、自動的に閉じられるようにする正当な理由がある場合のように思えます。

于 2008-11-12T04:11:59.620 に答える
8

はい、ファイル記述子を閉じて、すべてのヒープ メモリを解放します。OS がクリーンアップすることがわかっている場合でも、valgrind または同様のツールを実行すると、結果に多くのノイズが表示されなくなります。 「合法的な」fdリークを簡単に認識できます。

于 2008-11-12T05:20:53.397 に答える
6

組み込みプラットフォームの美しい世界では、何が起こるかを予測するのは非常に困難です。ただし、私があなたの状況にあった場合は、ファイル ID が実際に解放されているかどうかを手動でテストするだけです。また、スペースが重要な場合は、この事実を別の場所に文書化できます。

于 2008-11-12T05:10:39.190 に答える
6

The one concern I would have with regard to leaving closing off file-descriptors to automatic cleanup, would be how much you care about any data you've written to said file-descriptors and if you reasonably can deal with a failure to write.

write() need not block (depending on how it were open()ed in the first place) and wait for data to successfully commit, so there are cases where close can fail because the underlying sub-system fails to commit the pending write, and thus close exits with failure and sets errno to EIO, and depending on what you just wrote, you may or may not want to take some corrective action.

Admittedly, this is a corner case where you REALLY care about data consistency, i.e. a DBMS type applications or reporting sucess/failure of a backup. In many (most?) cases it doesn't really matter all that much, and you'll be fine leaving off close() to process cleanup/exit.

于 2014-01-22T01:30:35.683 に答える
4

男 3 出口:

....
All open stdio(3) streams are flushed and closed.  Files created by tmpfile(3) are removed.

したがって、メインを離れると、メインの戻り値で exit 関数が効果的に呼び出されると思います。私はそれが悪いスタイルだと主張しますが。個人的には、取得したリソースを常に明示的に解放/クローズしています。

于 2008-11-12T04:09:48.267 に答える