4

I m developing a C application running on linux system (kernel 3.4.11)

In my application, I m opening a server socket on a thread. And I m opening a fork() in which I execute a shell command with execvp() in the main thread.

Opening a fork() will inherit the socket file descriptor in the child. And this could cause problems according to many topics on the net. In my case If I close my application I can see with netstat that the socket is assigned to another daemon (another random daemon).

In fact there is many solutions for a such issue:

1) close the socket on the beginning of the fork() child:

if ((pid = fork()) == -1)
    return -1;

if (pid == 0) {
    /* child */

    close(socket_desc);

2) Use fcntl() and FD_CLOEXEC when opening the socket in the parent

socket_desc = socket(AF_INET , SOCK_STREAM , 0);
fcntl(socket_desc, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);

3) Use O_CLOEXEC in the socket() function:

socket_desc = socket(AF_INET , SOCK_STREAM|O_CLOEXEC , 0);

What's the best solution? and why?

Any other better solution is welcome.

MOHAMED
  • 41,599
  • 58
  • 163
  • 268

1 Answers1

3

If you control all the code, these make no difference.

Use the first solution if someone else gives you a socket you don't know how it was created.

Use the second, if you write a module to which someone else transmit you a socket, and you want to pass it to another module you don't control but you suspect to fork()/exec().

Use the third if you are the creator of the socket and need to pass it to another module that you suspect to fork()/exec().

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69