crestart

How to restart or start a process with closing all file descriptors in C


I want to restart my process cleanly. So I tried to call execv().

It seemed to work well. However, it keeps sockets and files opened. Is there a way to restart (this) process and close all file/sockets?

I don't want to make a zombie process, I don't use fork().


Solution

  • Just like any other file descriptors, sockets are not closed across exec or fork. If you want them closed, you will need to close them yourself. There are three possible approches.

    The cleanest solution is to keep track of all your sockets and close them before calling exec. Depending on your application, this might or might not be possible.

    Another solution is to set the "close on exec" flag on your sockets just after creating them, using a pair of fcntl calls (F_GETFD, add FD_CLOEXEC, then F_SETFD). Do not forget the sockets you obtained from accept.

    If that cannot be done, you can brutally close all of your file descriptors just before calling exec using something like the following:

    n = sysconf(_SC_OPEN_MAX);
    for(i = 3; i < n; i++)
        close(i);