So I have a java program that calls a C program through ProcessBuilder, and I need the C program to inform tha Java program when something happens. I have the following code for the java prog:
String cmd[] = //string to run the c program in the terminal, no probs here
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println(bufferedReader.ready());
System.out.println(bufferedReader.readLine());
The c program at a given point will have to inform the java program of something. I have tried many things like
char Buff[] = "output";
write(0, Buff, strlen(Buff)+1);
write(1, Buff, strlen(Buff)+1);
printf("output\n");
But I cant get the java program to read this, the only output I get is
false
null
The Java program won’t see the output until buffers are flushed.
Buffering at the level of
writeis OS dependent and even within the same OS, different kinds of streams may have different default buffering modes. In Linux the documents imply awriteto a pipe will immediately be readable by the other process, andProcessBuilderuses a pipe at least in Android.It’s likely that if you use
stdio.hthatfflushwill portably push data all the way out to the socket or pipe. E.g. I have had success withfflushfor this purpose in Android usingProcessBuilder.Line buffering is another possible choice for the OS. In this case appending
\nto your messages may have an effect.By the way, mixing
writeandprintfcalls in the same program is asking for trouble. And as has been mentioned,write(0is an attempt to write tostdin, andstrlen(buf)+1is causing a final zero byte to be sent to the Java program, which is unlikely to be what you want.