1 |
# |
---|
2 |
# Copyright (C) 2008 Red Hat, Inc. |
---|
3 |
# Author: Andreas Thienemann <athienem@redhat.com> |
---|
4 |
# |
---|
5 |
# This program is free software; you can redistribute it and/or modify |
---|
6 |
# it under the terms of the GNU Library General Public License as published by |
---|
7 |
# the Free Software Foundation; version 2 only |
---|
8 |
# |
---|
9 |
# This program is distributed in the hope that it will be useful, |
---|
10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
12 |
# GNU Library General Public License for more details. |
---|
13 |
# |
---|
14 |
# You should have received a copy of the GNU Library General Public License |
---|
15 |
# along with this program; if not, write to the Free Software |
---|
16 |
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
---|
17 |
# Copyright 2004, 2005 Red Hat, Inc. |
---|
18 |
# |
---|
19 |
# AUTHOR: Andreas Thienemann <athienem@redhat.com> |
---|
20 |
# |
---|
21 |
|
---|
22 |
import os, sys |
---|
23 |
|
---|
24 |
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): |
---|
25 |
'''Daemonize the process''' |
---|
26 |
try: |
---|
27 |
pid = os.fork() |
---|
28 |
if pid > 0: |
---|
29 |
sys.exit(0) # Exit first parent. |
---|
30 |
except OSError, e: |
---|
31 |
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) ) |
---|
32 |
sys.exit(1) |
---|
33 |
|
---|
34 |
# Decouple from parent environment. |
---|
35 |
os.chdir("/") |
---|
36 |
os.umask(0) |
---|
37 |
os.setsid() |
---|
38 |
|
---|
39 |
# Do second fork. |
---|
40 |
try: |
---|
41 |
pid = os.fork() |
---|
42 |
if pid > 0: |
---|
43 |
sys.exit(0) # Exit second parent. |
---|
44 |
except OSError, e: |
---|
45 |
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) ) |
---|
46 |
sys.exit(1) |
---|
47 |
|
---|
48 |
# Now I am a daemon! |
---|
49 |
|
---|
50 |
# Redirect standard file descriptors. |
---|
51 |
si = open(stdin, 'r') |
---|
52 |
so = open(stdout, 'a+') |
---|
53 |
se = open(stderr, 'a+', 0) |
---|
54 |
os.dup2(si.fileno(), sys.stdin.fileno()) |
---|
55 |
os.dup2(so.fileno(), sys.stdout.fileno()) |
---|
56 |
os.dup2(se.fileno(), sys.stderr.fileno()) |
---|
57 |
|
---|
58 |
|
---|
59 |
#convert string to hex |
---|
60 |
def toHex(s): |
---|
61 |
lst = [] |
---|
62 |
for ch in s: |
---|
63 |
hv = hex(ord(ch)).replace('0x', '') |
---|
64 |
if len(hv) == 1: |
---|
65 |
hv = '0'+hv |
---|
66 |
lst.append(hv) |
---|
67 |
|
---|
68 |
return reduce(lambda x,y:x+y, lst) |
---|
69 |
|
---|
70 |
#convert hex repr to string |
---|
71 |
def toStr(s): |
---|
72 |
return s and chr(atoi(s[:2], base=16)) + toStr(s[2:]) or '' |
---|
73 |
|
---|