| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# hashfork.py |
| 4 |
# |
| 5 |
# by Hubert Chan, March 2005 |
| 6 |
# |
| 7 |
# This file is hereby placed in the public domain. |
| 8 |
|
| 9 |
import os |
| 10 |
import signal |
| 11 |
import sys |
| 12 |
|
| 13 |
if len(sys.argv) < 3: |
| 14 |
print "Run multiple instances of hashcash in parallel" |
| 15 |
print "usage:" |
| 16 |
print " ", sys.argv[0], "<processes> <hashcash command line arguments>" |
| 17 |
print |
| 18 |
print " <processes> is the number of hashcash processes to start" |
| 19 |
print " <hashcash command line arguments> is the command line argumens to pass to" |
| 20 |
print " hashcash. Note that the -m option will be automatically added, and" |
| 21 |
print " so does not need to be specified." |
| 22 |
print |
| 23 |
print "Note: you MUST specify a resource on the command line." |
| 24 |
sys.exit () |
| 25 |
|
| 26 |
NUM_PROCS = int (sys.argv[1]) |
| 27 |
|
| 28 |
del (sys.argv[0:2]) |
| 29 |
sys.argv.insert(0, "hashcash") |
| 30 |
sys.argv.insert(1, "-m") |
| 31 |
|
| 32 |
children = [ ] |
| 33 |
pipes = [ ] |
| 34 |
|
| 35 |
for i in range (NUM_PROCS): |
| 36 |
pipe = os.pipe () # create a pipe to communicate with the child |
| 37 |
pid = os.fork () |
| 38 |
if pid: |
| 39 |
# parent |
| 40 |
children.append (pid) |
| 41 |
os.close (pipe[1]) # close the write end of the pipe |
| 42 |
pipes.append (os.fdopen (pipe[0])) |
| 43 |
# print "process", pid, "started" |
| 44 |
else: |
| 45 |
# child |
| 46 |
os.close (pipe[0]) # close the read end of the pipe |
| 47 |
os.dup2 (pipe[1], 1) # redirect stdout to the pipe |
| 48 |
os.close (pipe[1]) |
| 49 |
os.execvp ("hashcash", sys.argv) |
| 50 |
|
| 51 |
status = os.wait () |
| 52 |
|
| 53 |
#print "process", status[0], "exited.\nkilling all children." |
| 54 |
|
| 55 |
for i in range (NUM_PROCS): |
| 56 |
# print children[i] |
| 57 |
if children[i] == status[0]: |
| 58 |
print (pipes[i].readline ()), |
| 59 |
try: |
| 60 |
os.kill (children[i], signal.SIGKILL) |
| 61 |
except OSError: # kill raises an OSError when the process already exited |
| 62 |
pass |