Re: How to send messages to a child process
Odd. The documentation for OutputStream says that the flush method
does nothing. http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html#flush()
I thought I'd checked whether flush() solves the problem, and it
didn't. After you both recommended flush(), I gave it a second try. I
wrote new trial Java and this time an external c program, both
included below. Now it's working. Messages get sent to the c program
and written to output.txt continuously, while without os.flush();,
they all arrive only when the os is closed. I don't know if this is
because I'm currently working on Linux at home rather than Mac at
work, but I'll find out tomorrow.
So, at the moment, this does appears solved. Thanks. I hope :)
// Test.java
import java.io.*;
public class Test
{
public static void main( String args[] ) throws Exception
{
Runtime r = Runtime.getRuntime();
Process p = r.exec( new String[] { "./test" } );
OutputStream os = p.getOutputStream();
for ( int index = 0; index < 100; index++ )
{
String message = "Message #" + (index+1) + "\n";
System.out.println( "Java Program sending: " + message );
os.write( message.getBytes() );
os.flush();
Thread.sleep( 500 );
}
os.close();
p.waitFor();
}
}
// test.c
#include <stdio.h>
#include <string.h>
int main( int argc, char *argv[] )
{
char buffer[1024];
int outFD;
outFD = creat( "output.txt", 0600 );
while( fgets( buffer, 1024, stdin ))
{
write( outFD, buffer, strlen( buffer ));
}
close( outFD );
}