在Windows下的Java应用程序中编写C控制台应用程序

如何在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,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 ? "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,ex);
    }
}

Java端似乎工作正常,但我没有收到C端的字符串.

在这里做错了吗?如何在Windows下将字符串数据从Java发送到C控制台应用程序?

最佳答案
写完5个字符串后,为什么不刷新Java端的输出流?

proc.getoutputStream().flush();

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...