0

蟒蛇脚本:

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 中运行脚本

python script.py 睡眠 100

并输入一个kill字符串,进程成功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

4

1 回答 1

0

尝试添加:

process.getOutputStream().flush();

或者,另一种方法:

PrintWriter outputWriter = new PrintWriter(process.getOutputStream(),true);
outputWriter.println("kill");
于 2013-02-22T13:34:35.980 回答