Daemonization
This commit is contained in:
parent
4df94c8793
commit
8500b77024
|
@ -5,6 +5,8 @@ import os
|
||||||
import tempfile
|
import tempfile
|
||||||
import mailcap
|
import mailcap
|
||||||
import sys
|
import sys
|
||||||
|
import argparse
|
||||||
|
import daemon
|
||||||
|
|
||||||
sockpath = "mailcap.sock"
|
sockpath = "mailcap.sock"
|
||||||
|
|
||||||
|
@ -97,23 +99,43 @@ class Server(object):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
if len(sys.argv) > 1:
|
parser = argparse.ArgumentParser()
|
||||||
if sys.argv[1] == "-h":
|
parser.add_argument('--pid', '-p', default=os.path.join(os.environ['HOME'], '.mailcap.pid'))
|
||||||
print("Usage: %s [socket_path = mailcap.sock]" % (sys.argv[0],))
|
parser.add_argument('--action', '-a', default='run', choices=['run', 'kill'])
|
||||||
|
parser.add_argument('--no-daemonize', '-n', action='store_true')
|
||||||
|
parser.add_argument('--socket', '-s', default=os.path.join(os.environ['HOME'], '.mailcap.sock'))
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.action == 'kill':
|
||||||
|
if os.path.exists(args.socket):
|
||||||
|
os.remove(args.socket)
|
||||||
|
if os.path.exists(args.pid):
|
||||||
|
pid = int(open(args.pid).read())
|
||||||
|
try:
|
||||||
|
os.kill(pid, 3)
|
||||||
|
except ProcessLookupError as e:
|
||||||
|
print("Failed to kill process with pid %d:" % (pid,), str(e))
|
||||||
|
os.remove(args.pid)
|
||||||
|
if os.path.exists(args.socket):
|
||||||
|
os.remove(args.socket)
|
||||||
|
elif args.action == 'run':
|
||||||
|
if os.path.exists(args.pid):
|
||||||
|
print("Already running with pid %d" % (int(open(args.pid).read()),))
|
||||||
exit()
|
exit()
|
||||||
else:
|
if os.path.exists(args.socket):
|
||||||
sockpath = sys.argv[1]
|
os.remove(args.socket)
|
||||||
if os.path.exists(sockpath):
|
|
||||||
os.remove(sockpath)
|
with daemon.DaemonContext(detach_process=not args.no_daemonize, files_preserve=[1,2]):
|
||||||
sv = Server(sockpath)
|
sv = Server(args.socket)
|
||||||
caps = mailcap.getcaps()
|
caps = mailcap.getcaps()
|
||||||
while True:
|
open(args.pid, "w+").write(str(os.getpid()))
|
||||||
rv = sv.next_file()
|
while True:
|
||||||
if rv:
|
rv = sv.next_file()
|
||||||
f, mime = rv
|
if rv:
|
||||||
print(f, mime)
|
f, mime = rv
|
||||||
match = mailcap.findmatch(caps, mime.split(';')[0], filename=f)
|
print(f, mime)
|
||||||
if match and match[0]:
|
match = mailcap.findmatch(caps, mime.split(';')[0], filename=f)
|
||||||
os.system(match[0])
|
if match and match[0]:
|
||||||
if 'nodelete' not in match[1]:
|
os.system(match[0])
|
||||||
os.remove(f)
|
if 'nodelete' not in match[1]:
|
||||||
|
os.remove(f)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user