【问题标题】:java Runtime.exec python and thread in python not runjava Runtime.exec python和python中的线程不运行
【发布时间】:2013-02-22 10:59:29
【问题描述】:

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
        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 sleep 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
爪哇:1.6.0_34
蟒蛇:2.7.3

【问题讨论】:

  • 浏览从exec info. page 链接的Java World 文章并实施建议。这样做可能会解决问题或为您(或我们)提供足够的信息来解决问题。

标签: java python multithreading runtime.exec pid


【解决方案1】:

尝试添加:

process.getOutputStream().flush();

或者,另一种方法:

PrintWriter outputWriter = new PrintWriter(process.getOutputStream(),true);
outputWriter.println("kill");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多