unexplored
unexplored

Reputation: 1424

Launch a process without consuming its output

I used this line to execute a python script from a java application:

Process process = Runtime.getRuntime().exec("python foo.py", null, directory);

The script runs a TCP server that communicates with my java app and other clients.

When I was debugging the script I had a few console prints here and there and everything was fine. As soon as the script was launched from Java Code, after a fixed time my TCP server was not responding. Following some time of debugging and frustration I removed my prints from the script and everything worked as expected.

It seems that there is some memory allocated for the process' standard output and error stream and if you don't consume it the process gets stuck while trying to write to a full buffer.

How to launch the process so that I don't have to consume the standard output stream? I'd like to keep the prints though for debugging, but don't want to start a thread that reads a stream that I don't need.

Upvotes: 1

Views: 524

Answers (3)

jenaiz
jenaiz

Reputation: 547

I did some similar in the past and I redirect the exit of the process to a particular file log relative with the process. Later you could see what is happening. And you could maintenance your trace of your python script.

Upvotes: 0

Pavan
Pavan

Reputation: 1247

Java exposes ProcessBuilder. This is something you can use to execute what you want. This does a fork-exec and also lets you handle the output and error streams.

The fact that your process hangs is not because of java. Its a standard problem where your process is blocked because the stream is full and no one is consuming it.

Try using the ProcessBuilder with a thread that reads the streams.

Upvotes: 1

erickson
erickson

Reputation: 269697

You have to consume the child process's output, or eventually it will block because the output buffer is full (don't forget about stderr, too). If you don't want to modify your Java program to consume it, perhaps you could add a flag to your script to turn off debugging altogether or at least direct it to a file (which could be /dev/null).

Upvotes: 2

Related Questions