Use O_CLOEXEC / SOCK_CLOEXEC for almost all file descriptors.

The presumption is that all file descriptors should be created with
the close-on-exec flag set.  The only exception are file descriptors
that we want passed through to exec'd subprocesses (mainly pipes and
stdin/stdout/stderr).

For open calls, we pass O_CLOEXEC as an extra flag, eg:

  fd = open ("foo", O_RDONLY|O_CLOEXEC);

This is a Linux-ism, but using a macro we can easily make it portable.

For sockets, similarly:

  sock = socket (..., SOCK_STREAM|SOCK_CLOEXEC, ...);

For accepted sockets, we use the Linux accept4 system call which
allows flags to be supplied, but we use the Gnulib 'accept4' module to
make this portable.

For dup, dup2, we use the Linux dup3 system call, and the Gnulib
modules 'dup3' and 'cloexec'.
This commit is contained in:
Richard W.M. Jones
2012-03-14 19:30:46 +00:00
parent 13e7a1b400
commit 606732d02e
37 changed files with 129 additions and 74 deletions

View File

@@ -223,7 +223,7 @@ rc_listen (void)
pid = getpid ();
create_sockpath (pid, sockpath, sizeof sockpath, &addr);
sock = socket (AF_UNIX, SOCK_STREAM, 0);
sock = socket (AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
if (sock == -1) {
perror ("socket");
exit (EXIT_FAILURE);
@@ -246,7 +246,7 @@ rc_listen (void)
*/
close_stdout ();
s = accept (sock, NULL, NULL);
s = accept4 (sock, NULL, NULL, SOCK_CLOEXEC);
if (s == -1)
perror ("accept");
else {
@@ -351,7 +351,7 @@ rc_remote (int pid, const char *cmd, size_t argc, char *argv[],
create_sockpath (pid, sockpath, sizeof sockpath, &addr);
sock = socket (AF_UNIX, SOCK_STREAM, 0);
sock = socket (AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
if (sock == -1) {
perror ("socket");
return -1;