I am trying to run a c++ executable from my Java web application. When I go the relevant page it executes the commands and runs the executable but does not produce any output.
Here is my code:
URL createWav = QRcodeController.class.getClassLoader().getResource("createWav");
log.info("The path of the c++ executable obtained: "+ createWav.getPath());
Process p1 = Runtime.getRuntime().exec("chmod 777 " + createWav.getPath());
p1.waitFor();
int exitVal=1;
try {
Process p2 = Runtime.getRuntime().exec(createWav.getPath(), args);
exitVal = p2.waitFor();
}
catch (Exception e)
{
log.error(e.getStackTrace());
}
if(exitVal == 1)
throw new Exception("Error in c++ program");
It does not throw any error so the c++ program runs fine but it does not produce the file it is supposed to. When I run the same command from the command line in the same machine it works perfectly producing the required file. I am not sure what I am doing wrong.
The C++ program is writing its output to a pipe, not the standard output of the Java program. Use Process.getOutputStream() to access that stream or, with Java 1.7, employ a
ProcessBuilderwhere you can use redirectOutput like this:In case your C++ program might write things to its standard error stream, you should probably deal with that in the same way.
Also note that leaving either of these streams connected to a pipe and not reading from that pipe might cause your application to block on output if the buffer associated with the pipe becomes full. To simply ignore output, you’d have to explicitely redirect it to
/dev/null. That’s not your aim just now, but it might be in a different situation.