2

I am doing a project. But I found in the source code there are so many file descriptor left unclosed. The first glance of it, I thought this is not good. After I googled, someone says, if there are some buffer behind this fd, don't close it or something bad will happen. I am not sure about this. So some can give some advice?

Should the file descriptor be closed once used? Are there any rules about usage of file descriptor?

2

Yes, it's a good idea to close file descriptors as soon as you no longer need them if only to release the associated resources and avoid reaching limits.

Now, some file descriptors may be open through some APIs, and you should use that same API to close them (not use the close(2) system call).

A typical such API is stdio in C (all the fopen, printf, fputs...). For instance, if a file was opened with fopen(3) (which returns a FILE* datatype, not a file descriptor but will have created a fd underneath), you'll want to close if with fclose(thatFILE) (which will flush all the buffers), not close(fileno(thatFILE)) which would close the fd under stdio's feet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.