When should I use O_CLOEXEC when I open file in Linux?

Bush picture Bush · Mar 16, 2013 · Viewed 16.5k times · Source

My process forks several times, and each time the child will exec - means I want it to run some other program.

In the main process I open a file descriptor with the open() syscall.

Would it be correct to give it a flag O_CLOEXEC so the new program that I run with exec() wouldn't has the fd resource?

Answer

user25148 picture user25148 · Mar 16, 2013

Yes, unless you need the program you exec to have access to that file descriptor. You can also close the file descriptor manually in the child process before calling exec, but that's more error prone.