Skip to content

Commit

Permalink
Fixed pid file creation sequence.
Browse files Browse the repository at this point in the history
  • Loading branch information
yurivict committed May 15, 2015
1 parent 5608176 commit 61ad1a5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 16 deletions.
19 changes: 9 additions & 10 deletions tiny-dhcp-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@ def usage():
usage()
for opt,arg in opts:
if opt in ("-l", "--log"):
arg_log_file=arg
arg_log_file = arg
if opt in ("-p", "--pid"):
arg_pid_file=arg
arg_pid_file = arg
if opt in ("-d", "--daemonize"):
arg_daemonize=True
arg_daemonize = True
if opt in ("-u", "--unprivileged"):
arg_unprivileged=True
arg_unprivileged = True

## HDCP/BOOTP format
BOOTREQUEST = 1
Expand Down Expand Up @@ -103,10 +103,11 @@ def log_discard(what):
## MAIN
##

## permissions
if not os.geteuid()==0:
sys.exit("Only root can run tiny-dhcp-server")

## command line arguments
## command line arguments: interfaces
if len(sys.argv) < 2:
sys.exit('Usage: '+sys.argv[0]+' <interface1> {, <interface2> ...}')

Expand Down Expand Up @@ -136,12 +137,10 @@ def log_discard(what):
sock.setsockopt(socket.IPPROTO_IP, socket_IP_RECVIF, 1)
sock.bind(('0.0.0.0', 67))

## daemonize
## daemonize and write pid file
if arg_daemonize:
tu.do_daemonize()

## pid file
if arg_pid_file is not None:
tu.do_daemonize(arg_pid_file)
elif arg_pid_file is not None:
tu.write_pid_file(arg_pid_file)

## lose privileges if requested
Expand Down
17 changes: 11 additions & 6 deletions tiny_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import os, pwd, grp, sys
import signal

def drop_privileges2(uid_name, gid_name, files):
def drop_privileges(uid_name, gid_name, files):
# get the uid/gid from the name
new_uid = pwd.getpwnam(uid_name).pw_uid
new_gid = grp.getgrnam(gid_name).gr_gid
Expand All @@ -25,9 +25,9 @@ def drop_privileges2(uid_name, gid_name, files):
os.umask(0o077)

def drop_privileges(files):
drop_privileges2('nobody', 'nogroup', files)
drop_privileges('nobody', 'nogroup', files)

def do_daemonize():
def do_daemonize(pid_file):
pid = os.fork()
if (pid > 0):
sys.exit(0); # exit first parent
Expand All @@ -37,14 +37,19 @@ def do_daemonize():

pid = os.fork()
if pid > 0:
if pid_file is not None:
write_pid_file2(pid_file, pid)
sys.exit(0); # exit from second parent

def write_pid_file(f):
pid = str(os.getpid())
def write_pid_file2(f, pid):
p = str(pid)
f = open(f, 'w')
f.write(pid)
f.write(p)
f.close()

def write_pid_file(f):
write_pid_file2(f, os.getpid())

def exit_gracefully(signum, frame, original_sigint, log):
log('exiting on signal %d' %signum)
sys.exit(1)
Expand Down

0 comments on commit 61ad1a5

Please sign in to comment.