I'm writing a program that executes another Java program by using the Class and Method classes to invoke the main method. This other program then tries to read from System.in. In order to pass arguments to the program, I set System.in to a PipedInputStream that is connected to a PipedOutputStream. I pass the arguments the other program requests to the PipedOutputStream, then invoke the main method.
However, as soon as the method is invoked, the program deadlocks. Why is that? Theoretically, the other program should have access to the arguments, since they're already available in the PipedInputStream.
I can't change the way the other program reads the input, so this solution wouldn't work.
Here some example code:
The part where I assign the PipedStreams
PipedInputStream inputStream = new PipedInputStream();
PipedStringOutputStream stringStream = new PipedStringOutputStream(); // custom class
try {
stringStream.connect(inputStream);
} catch (IOException e2) {
e2.printStackTrace();
}
System.setIn(inputStream);
The part where I invoke the method:
Class main = classes.get(className);
try {
Method m = main.getMethod("main", String[].class);
// write all parameters to System.in
String[] params = getParams(); // custom method, works (params is not empty)
for(int j = 0; j < params.length; j++) {
stringStream.write(params[j]);
}
params = null;
m.invoke(null, (Object) params); // this is were the program stops
} catch(Exception e) {}
The PipedStringOutputStream class:
public class PipedStringOutputStream extends PipedOutputStream {
public void write(String output) throws IOException {
this.write((output + "\n").getBytes());
flush();
}
}
My test program that reads from System.in:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
}
}
So what is the problem? Do I have to start the Streams in Threads? Why doesn't the other program read the input from the PipedInputStream?