0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
kdlan
  • 15
  • 4
  • Go through the Java World article linked from the [exec info. page](http://stackoverflow.com/tags/runtime.exec/info) & implement the recommendations. Doing so will probably either solve the problem or provide you (or us) enough information to solve it. – Andrew Thompson Feb 22 '13 at 11:33

1 Answers1

0

Try adding:

process.getOutputStream().flush();

Or, another approach:

PrintWriter outputWriter = new PrintWriter(process.getOutputStream(),true);
outputWriter.println("kill");
Pace
  • 41,875
  • 13
  • 113
  • 156