Repository navigation
Expand file tree
/
Copy pathforkpool
More file actions
executable file
·130 lines (95 loc) · 3.81 KB
/
Copy pathforkpool
File metadata and controls
executable file
·130 lines (95 loc) · 3.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3
from os import fork, execvp, kill, pipe, read, close, waitpid, getpid, environ, set_blocking, set_inheritable, WNOHANG, WEXITSTATUS
from signal import signal, set_wakeup_fd, SIG_DFL, SIGQUIT, SIGHUP, SIGUSR1
from select import select
from time import time
import optparse
import sys
signals = []
log_level = 0
def main( argv, stdin, stdout, stderr ):
global signals, log_level
def logging_option( option, opt_str, value, parser ):
if option.get_opt_string() == '--verbose':
parser.values.log_level += 1
elif option.get_opt_string() == '--quiet':
parser.values.log_level -= 1
optp = optparse.OptionParser()
optp.add_option( '-c', '--count', help="Keep N concurrent child processes around.", type='int', default=1, action='store' )
optp.add_option( '-s', '--relay-signals', help="Relay certain signals to children. Currently just SIGHUP.", action='store_true' )
optp.add_option( '-L', '--log-level', help="Set logging level.", type='int', default=0, action='store' )
optp.add_option( '-v', '--verbose', help="Increase logging verbosity.", action='callback', callback=logging_option )
optp.add_option( '-q', '--quiet', help="Decrease logging verbosity.", action='callback', callback=logging_option )
opts, args = optp.parse_args( args=argv[1:] )
log_level = opts.log_level
signal( SIGQUIT, signal_handler )
signal( SIGHUP, signal_handler )
signal( SIGUSR1, signal_handler )
signal_rfd, signal_wfd = pipe()
set_blocking(signal_rfd, False), set_blocking(signal_wfd, False)
set_inheritable(signal_rfd, False), set_inheritable(signal_wfd, False)
set_wakeup_fd(signal_wfd)
max_children = opts.count
children = dict() # key = child's pid, value = child's exit pipe fd
set_spawn_time()
while max_children or len(children):
# Process and clear pending signals.
if SIGQUIT in signals:
log( 1, "got SIGQUIT, winding down" )
max_children = 0
if SIGHUP in signals:
log( 1, "got SIGHUP, children should exit gracefully" )
if opts.relay_signals:
for pid in children.keys():
kill( pid, SIGHUP )
set_spawn_time()
if SIGUSR1 in signals:
pids = [ "%d" % pid for pid in children.keys() ]
log( 2, "info: (%d/%d) children: %s" % (len(children),max_children,",".join(pids)) )
signals[:] = []
# Replenish children up to the limit.
while len(children) < max_children:
rfd, wfd = pipe()
set_blocking(rfd, False), set_blocking(wfd, False)
set_inheritable(rfd, False), set_inheritable(wfd, True)
pid = fork()
if pid:
close(wfd)
children[pid] = rfd
log( 1, "child %d (%d/%d) started" % (pid,len(children),max_children) )
else:
execvp(args[0],args)
# Wait for signals or exited children.
rlist = [signal_rfd] + list(children.values())
rlist, wlist, xlist = select(rlist, [], [], None)
if signal_rfd in rlist:
read(signal_rfd, 1024)
# Reap children and report their status.
statuses = reap(children)
for pid, status in statuses.items():
rc = WEXITSTATUS(status)
log( 1, "child %d (%d/%d) exited %d" % (pid,len(children),max_children,rc) )
reap(children)
return 0
def reap( children ):
statuses = dict()
while len(children):
pid, status = waitpid(-1, WNOHANG)
if not pid:
break
statuses[pid] = status
close(children[pid])
del children[pid]
return statuses
def signal_handler( signum, frame ):
global signals
signals.append(signum)
def set_spawn_time():
environ['FORKPOOL_SPAWN_TIME'] = '%d' % time()
def log( level, msg ):
global log_level
if level > log_level: return
prog = sys.argv[0].split('/')[-1]
print("%s/%05d: {L%d} %s" % (prog,getpid(),level,msg), file=sys.stderr)
if __name__ == '__main__':
exit( main(sys.argv,sys.stdin,sys.stdout,sys.stderr) )