How can I send string data from Java to a C++ console application under Windows? I am trying to do this:
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String o = ...;
proc.getOutputStream().write(o.getBytes());
But I never see it on the C++ side when I do this:
ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0)
ReadFile
never returns.
What follows is further elaboration and sample code.
I have written a simple C++ console (Win32) application which reads from STDIN and performs actions based on input.
Now I want to write a Java application to "drive" the C++ application. The Java applicaton should:
Runtime.exec()
My Java application seems to be working, but the C++ application never receives any data on STDIN.
Here is the C++ application:
int main()
{
ofstream f("c:\\temp\\hacks.txt");
HANDLE stdin_h = GetStdHandle(STD_INPUT_HANDLE);
DWORD file_type = GetFileType(stdin_h);
if( file_type != FILE_TYPE_CHAR )
return 42;
f << "Pipe" << endl;
for( bool cont = true; cont; )
{
char buf[64*1024] = {};
DWORD bytes = 0;
if( ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0) )
{
string in(buf,bytes);
cout << "Got " << in.length() << " bytes: '" << in << "'" << endl;
f << "Got " << in.length() << " bytes: '" << in << "'" << endl;
if( in.find('Q') )
cont = false;
}
else
{
cout << "Err " << GetLastError() << " while reading file" << endl;
f << "Err " << GetLastError() << " while reading file" << endl;
}
}
}
And here is the Java side:
public static void main(String[] args) {
Runtime rt =Runtime.getRuntime();
try {
Process proc = rt.exec("c:\\dev\\hacks\\x64\\debug\\hacks.exe");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
int a = 0;
while(a < 5)
{
String o = (a == 4 ? "Q\n" : "A\n");
proc.getOutputStream().write(o.getBytes());
System.out.println("Wrote '" + o + "'");
++a;
}
try {
proc.waitFor();
// TODO code application logic here
} catch (InterruptedException ex) {
Logger.getLogger(Java_hacks.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Java_hacks.class.getName()).log(Level.SEVERE, null, ex);
}
}
The Java side seems to be working correctly, but I'm not ever receiving the strings on the C++ side.
Am I doing something wrong here? How can I send string data from Java to a C++ console application under Windows?
Why are you not flushing the output stream on the Java side after writing 5 strings?
proc.getOutputStream().flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With