daemon: Close standard file descriptors when daemonizing.
authorBen Pfaff <blp@nicira.com>
Tue, 12 Jan 2010 22:10:11 +0000 (14:10 -0800)
committerBen Pfaff <blp@nicira.com>
Wed, 13 Jan 2010 00:03:35 +0000 (16:03 -0800)
Before SSH terminates, it waits for the PTYs that it creates for use as
stdin, stdout, and stderr to be closed.  When any of the Open vSwitch
daemons were started in the background over an SSH session, they held
those file descriptors open and thus the SSH session hung.  This commit
fixes the problem by closing those file descriptors, allowing SSH to
terminate.

lib/daemon.c

index 9a1be55..61754de 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2009 Nicira Networks.
+ * Copyright (c) 2008, 2009, 2010 Nicira Networks.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -282,6 +282,7 @@ daemonize_complete(void)
 {
     if (detach) {
         size_t bytes_written;
+        int null_fd;
         int error;
 
         error = write_fully(daemonize_fds[1], "", 1, &bytes_written);
@@ -294,6 +295,16 @@ daemonize_complete(void)
         if (chdir_) {
             ignore(chdir("/"));
         }
+
+        /* Close stdin, stdout, stderr.  Otherwise if we're started from
+         * e.g. an SSH session then we tend to hold that session open
+         * artificially. */
+        null_fd = get_null_fd();
+        if (null_fd >= 0) {
+            dup2(null_fd, STDIN_FILENO);
+            dup2(null_fd, STDOUT_FILENO);
+            dup2(null_fd, STDERR_FILENO);
+        }
     }
 }