Revision 8f765069 lib/utils.py

b/lib/utils.py
38 38
import itertools
39 39
import select
40 40
import fcntl
41
import resource
41 42

  
42 43
from cStringIO import StringIO
43 44

  
......
1080 1081
    return False
1081 1082
  time.sleep(duration)
1082 1083
  return True
1084

  
1085

  
1086
def Daemonize(logfile):
1087
  """Daemonize the current process.
1088

  
1089
  This detaches the current process from the controlling terminal and
1090
  runs it in the background as a daemon.
1091

  
1092
  """
1093
  UMASK = 077
1094
  WORKDIR = "/"
1095
  # Default maximum for the number of available file descriptors.
1096
  if 'SC_OPEN_MAX' in os.sysconf_names:
1097
    try:
1098
      MAXFD = os.sysconf('SC_OPEN_MAX')
1099
      if MAXFD < 0:
1100
        MAXFD = 1024
1101
    except OSError:
1102
      MAXFD = 1024
1103
  else:
1104
    MAXFD = 1024
1105

  
1106
  # this might fail
1107
  pid = os.fork()
1108
  if (pid == 0):  # The first child.
1109
    os.setsid()
1110
    # this might fail
1111
    pid = os.fork() # Fork a second child.
1112
    if (pid == 0):  # The second child.
1113
      os.chdir(WORKDIR)
1114
      os.umask(UMASK)
1115
    else:
1116
      # exit() or _exit()?  See below.
1117
      os._exit(0) # Exit parent (the first child) of the second child.
1118
  else:
1119
    os._exit(0) # Exit parent of the first child.
1120
  maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
1121
  if (maxfd == resource.RLIM_INFINITY):
1122
    maxfd = MAXFD
1123

  
1124
  # Iterate through and close all file descriptors.
1125
  for fd in range(0, maxfd):
1126
    try:
1127
      os.close(fd)
1128
    except OSError: # ERROR, fd wasn't open to begin with (ignored)
1129
      pass
1130
  os.open(logfile, os.O_RDWR|os.O_CREAT|os.O_APPEND, 0600)
1131
  # Duplicate standard input to standard output and standard error.
1132
  os.dup2(0, 1)     # standard output (1)
1133
  os.dup2(0, 2)     # standard error (2)
1134
  return 0

Also available in: Unified diff