Explicitly close file descriptors or let the OS close them in Unix C programming?

In Unix C programming, is it considered good practice to explicitly close file descriptors before the process completes, or is good practice instead allowing the OS to close the file and therefore avoid unnecessary code?

Which of the two is generally considered the preferred alternative?

Example:

int main (int argc, char* argv[])
{
    int sd;
    sd = socket(...);

    // Snip

   close(sd); // Good or bad practice?
   return 0;
}
+3
source share
7 answers

Typically, the code that performs opening and closing does not know if the process will exit immediately, so it is best to include explicit code.

Even if the code is in the top-level main () function, it will still be a good idea if you reuse the code.

+10

.

, , , , "".

stdin, stdout stderr, .

, UNIX " ".

+5

, , .

, , , close() , / .

+2

unix , , unix, .

, - , .

, ,

+2

, , .

. , () , , , , .

+1

, "", , , . , .

, , , , (, ). .

0

, , - . , , (, , ) stdout stderr, .

0

All Articles