写入 Windows 下 Java 应用程序中生成的控制台应用程序C++
Writing To C++ Console Application Spawned Within Java App Under Windows
如何在 Windows 下将字符串数据从 Java 发送到C++控制台应用程序? 我正在尝试这样做:
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String o = ...;
proc.getOutputStream().write(o.getBytes());
但是当我这样做时,我从来没有在C++方面看到它:
ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0)
ReadFile
永远不会回来。
接下来是进一步的阐述和示例代码。
我编写了一个简单的C++控制台(Win32)应用程序,该应用程序从STDIN读取并根据输入执行操作。
现在我想编写一个 Java 应用程序来"驱动"C++应用程序。 Java 应用程序应该:
- 使用
Runtime.exec()
启动C++应用程序 - 将字符串数据写入C++应用的 STDIN
- 重复直到为止。
我的 Java 应用程序似乎正在运行,但C++应用程序从未在 STDIN 上接收任何数据。
这是C++应用程序:
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;
}
}
}
这是Java方面:
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 ? "Qn" : "An");
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);
}
}
Java 端似乎工作正常,但我从未收到C++端的字符串。
我在这里做错了什么吗? 如何将字符串数据从 Java 发送到 Windows 下的C++控制台应用程序?
为什么在
写入 5 个字符串后不刷新 Java 端的输出流?
proc.getOutputStream().flush();
相关文章:
- C++控制台应用程序阻止退出
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- 如何在 Win32 C++控制台应用程序中调用 UWP 类库
- 是否可以从控制台应用程序使用 C++/WinRT 创建窗口?
- 如何创建一个使用开源c项目的c++控制台应用程序
- c ++控制台应用程序,如何在控制台外部打印字符
- 像 CPP 中的控制台一样的应用程序
- 调试控制台 ChessEngine.exe "used"在另一个应用程序(国际象棋 GUI)中
- 将控制台应用程序直接输出到Visual Studio而不是外部Windows控制台中
- 如何在 Win32 控制台应用程序中注册不可见的窗口类?
- 如何将从控制台应用程序C++回调设置为C++ COM DLL
- 使用代码在 AWS 开发工具包C++控制台应用程序上设置凭证
- 直接输入控制台应用程序
- C++调试控制台应用程序
- C++控制台应用程序调用C++/CLI静态库
- 如何在控制台应用程序中添加滚动功能以显示更大的输入
- C++应用程序控制台未退出
- 如何使用VSCode调试C++应用程序控制台应用程序
- 用于调试消息的跨平台GUI应用程序控制台
- 自定义应用程序控制台和stderr