写入 Windows 下 Java 应用程序中生成的控制台应用程序C++

Writing To C++ Console Application Spawned Within Java App Under Windows

本文关键字:应用程序 控制台 C++ Windows Java 写入      更新时间:2023-10-16

如何在 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 应用程序应该:

  1. 使用 Runtime.exec() 启动C++应用程序
  2. 将字符串数据写入C++应用的 STDIN
  3. 重复直到为止。

我的 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();