代码之家  ›  专栏  ›  技术社区  ›  northpole

运行时执行和自定义构建的RTF编辑器

  •  1
  • northpole  · 技术社区  · 15 年前

    我有一个类来管理RTF文档的创建,该类中的一个方法用一个XML文件调用RTF编辑器进行显示。

    除了一个用户以外,其他所有用户都可以访问此编辑器,而不会出现任何问题。这一个用户总是遇到应用程序挂起的问题。任何日志中都没有错误。通常,这种问题很容易识别、复制和纠正,但是,我不能在复制它的一生中,所以我的调试尝试失败了。

    基本上代码如下:

    int exitVal = CUBSRTFEditor.runRTFEditor("c:\\tmp\\control"+ap_doc_id+".xml", xml,"I:\\AppealsLetters.exe /process \"c:\\tmp\\control"+ap_doc_id+".xml\"");
    
    public static int runRTFEditor(String xmlLocation, String xmlContent, String executePath)
    {
        int exitVal = 0;
        createLocalFile(xmlLocation, xmlContent);
    
        try
        {
            System.out.println("executePath must = "+executePath);
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(executePath);
            System.out.println("after executePath runs");
    
            //exhaust that stream before waiting for the process to exit
            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            // read the ls output
            String line;
            while ((line = bufferedreader.readLine())!= null)
            {
                System.out.println(line);
            }
            exitVal = proc.waitFor();
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    
        CUBSRTFEditor.deleteTempFile(xmlLocation);
    
        return exitVal;
    }
    

    最后一个输出是第一个System.Out。当我获取XML文件并在任何其他PC上执行它时,它会毫无问题地执行。我在proc.getErrorstream()或proc.getOutputstream()中没有看到有用的信息。

    JDK关于这个问题的JavaDoc文档(exec hanging): 由于某些本机平台只为标准输入和输出流提供有限的缓冲区大小,因此如果不及时写入输入流或读取子进程的输出流,可能会导致子进程阻塞,甚至死锁。

    我尝试在等待进程退出之前耗尽该流,但这似乎没有帮助,因为它似乎永远不会到达该点(不显示第二个system.out)。

    我是否执行错误?我错过重要的东西了吗?任何关于如何从过程中获得更多信息的想法都是很好的。

    我被卡住了…

    2 回复  |  直到 12 年前
        1
  •  2
  •   BlairHippo    15 年前

    runtime.exec()是一个令人讨厌的小spud。我发现 this article (旧的,但仍然相关)是相当有用的。对于一些高度可移植的示例代码,您总是可以跳到第4页。:-)

    乍一看,您的代码需要同时处理proc.getOutputstream()和proc.getErrorstream(),这是在单独的线程中处理这些流的一个很好的理由。

        2
  •  0
  •   northpole    15 年前

    我想更新这个,因为这个更改今天已经投入生产,并且有效。基于Blairhippo的建议,我让它与一个匿名的内部类一起工作,创建一个独立的线程来消除错误和输入流。

    new Thread(new Runnable(){
        public void run()
        {
            try
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                String line;
                while ((line = br.readLine())!= null)
                {
                    System.out.println(line);
                }
            }
            catch (Throwable t)
            {
                t.printStackTrace();
            }
        }
    }).start();