java Runtime.exec python和python中的线程未运行
python脚本:java Runtime.exec python和python中的线程未运行,java,python,multithreading,runtime.exec,pid,Java,Python,Multithreading,Runtime.exec,Pid,python脚本: 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
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)
在bash中运行脚本
pythonscript.py睡眠100
并输入kill字符串,进程成功终止
但是在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();
python中的newThread似乎未运行,并且线程未接收到kill字符串
有人能告诉我为什么这不起作用吗?或者是否有其他方法(如os.setpgrp和os.killpg)来终止所有子进程
操作系统:ubuntu 12.04内核:3.2.0-37-generic
java:1.6.0_34
python:2.7.3
尝试添加:
process.getOutputStream().flush();
或者,另一种方法:
PrintWriter outputWriter = new PrintWriter(process.getOutputStream(),true);
outputWriter.println("kill");
浏览链接自的Java World文章&实现建议。这样做可能会解决问题,或者为您(或我们)提供足够的信息来解决问题。