When we perform a fork in Unix, open file handles are inherited, and if we don\'t need to use them we should close them. However, when we use libraries, file handles may be open
As mentioned on @Louis Gerbarg's answer, the libraries are probably expecting the file handles to be kept open on fork()
(which is supposed to be, after all, an almost identical copy of the parent process).
The problem most people have is on the exec()
which often follows the fork()
. Here, the correct solution is for the library which created the handles to mark them as close-on-exec (FD_CLOEXEC
).
On libraries used by multithread programs, there is a race condition between a library creating a file handle and setting FD_CLOEXEC
on it (another thread can fork()
between both operations). To fix that problem, O_CLOEXEC was introduced in the Linux kernel.