python script:
import os
import subprocess
import threading
import sys
command= sys.argv[1:]
command=" ".join(command)
def readValue():
print 'start receive command'
while True:
msg=raw_input()
print 'msg received: %s' % msg
if 'kill'==msg:
os.killpg(os.getpgid(p.pid),9)
newThread = threading.Thread(target = readValue, name = "readingThread" )
newThread.setDaemon(1)
newThread.start()
p=subprocess.Popen(command,shell=True,preexec_fn=os.setpgrp)
p.wait()
exitCode=p.poll()
sys.exit(exitCode)
run the script in bash
python script.py sleep 100
and input a kill string, the process success killed
But when run the script in java
Runtime runtime = Runtime.getRuntime();
Process process=runtime.exec("python script.py sleep 100");
Thread.sleep(1000);
process.getOutputStream().write("kill\n".getBytes());
process.waitFor();
The newThread in python seems not run and the kill string not received by the thread
Can anyone tell me why this not work? Or is there some other way like os.setpgrp and os.killpg to kill all the sub process
OS: ubuntu 12.04
kernel : 3.2.0-37-generic
java: 1.6.0_34
python: 2.7.3