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.