[mythtv] [Micropatch] Fix tiny daemon bug.

michael at optusnet.com.au michael at optusnet.com.au
Sat May 24 18:28:15 EDT 2003


Micropatch.

#1. Add an open("/dev/null") after the close(0) to ensure
that normal open()'s later in the program don't inadvertently
wind up in STDIN.

#2. Fix a small bug: If daemonize is set, but no logfile is
set, then stderr/stdout stay associated with /dev/tty. Fix
by dup'ing /dev/null to stderr and stdout.

#3. As a result of the above two changes, the split between
open'ing the pidfile and writing to it can go away.



diff -c -r mythtv-3/programs/mythbackend/main.cpp mythtv-4/programs/mythbackend/main.cpp
*** mythtv-3/programs/mythbackend/main.cpp	2003-05-23 15:58:43.000000000 +1000
--- mythtv-4/programs/mythbackend/main.cpp	2003-05-23 16:37:13.000000000 +1000
***************
*** 127,142 ****
          }
      }
      
-     ofstream pidfs;
-     if (pidfile != "") {
-         pidfs.open(pidfile.ascii());
-         if (!pidfs) {
-             perror("open(pidfile)");
-             return -1;
-         }
-     }
  
      close(0);
  
      if (daemonize)
          if (daemon(0, 1) < 0) {
--- 127,150 ----
          }
      }
      
  
+ 	/* Replace STDIN with /dev/null. */
+ 	/* We open it read/write because we may need to dup it to stdout/stderr later. */
+ 	/* The open() is guarenteed to return file descriptor 0 as a result of the close. */
      close(0);
+     if (open("/dev/null", O_RDWR) != 0) { 
+         cerr << "Failed to open /dev/null!\n";
+ 	exit(1);
+     }
+ 
+     if (logfd != -1) {
+         // Send stdout and stderr to the logfile
+         dup2(logfd, 1);
+         dup2(logfd, 2);
+     } else if (daemonize) { /* copy "/dev/null" to STDOUT and STDERR */
+ 	dup2(0, 1);
+ 	dup2(0, 2);
+     }
  
      if (daemonize)
          if (daemon(0, 1) < 0) {
***************
*** 144,160 ****
              return -1;
          }
  
! 
!     if (pidfs) {
          pidfs << getpid() << endl;
          pidfs.close();
      }
  
-     if (logfd != -1) {
-         // Send stdout and stderr to the logfile
-         dup2(logfd, 1);
-         dup2(logfd, 2);
-     }
  
      gContext = new MythContext(MYTH_BINARY_VERSION, false);
  
--- 152,169 ----
              return -1;
          }
  
! 	/* If we have a valid PID file, then write out the current PID to it. */
!     if (pidfile != "") {
!         ofstream pidfs;
!         pidfs.open(pidfile.ascii());
!         if (!pidfs) {
!             perror("open(pidfile)");
!             return -1;
!         }
          pidfs << getpid() << endl;
          pidfs.close();
      }
  
  
      gContext = new MythContext(MYTH_BINARY_VERSION, false);
  


More information about the mythtv-dev mailing list