Runtime.exec()在tomcat / web应用程序上无法正常工作

时间:2012-03-05 17:45:58

标签: java web-applications tomcat

我在WebApplication中运行.exe程序时遇到了奇怪的问题。它在控制台模式下工作正常。

我的exe应用程序代码:

            ...
            Console.WriteLine("before getEnvirement");
            IDictionary environmentVariables = Environment.GetEnvironmentVariables();
            foreach (DictionaryEntry de in environmentVariables)
            {
                Console.WriteLine("  {0} = {1}", de.Key, de.Value);
            }
            Console.WriteLine("before new Application");
            this.application = new App();
            Console.WriteLine("after new Application");
            ...

其中App()是来自COM库的类(当然我添加了引用)。

我的Java控制台/ WebApplication代码:

    try {
        String[] callAndArgs = {"C:\\temp\\program.exe", "arg1", "arg2"};
        Process p = Runtime.getRuntime().exec(callAndArgs);
        p.waitFor();
    } catch (IOException e) {
        System.out.println("IOException Error: " + e.getMessage());
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }

以“控制台模式”输出(正确):

before getEnvirement
  <all my envirements>
before new Application
after new Application

以“网络应用程序模式”输出(错误):

before getEnvirement
  Path = C:\Windows\system32; <...>
  TEMP = C:\Windows\TEMP

或当我删除getEnvirement代码(也很糟糕)时:

before getEnvirement
before new Application

exe应用程序不会在tomcat上关闭(我必须使用任务管理器来杀死它)

我的问题:为什么它在tomcat上无法正常工作?为什么exe程序在tomcat上运行时遇到系统环境问题?最后:为什么它在控制台模式下工作? :)

1 个答案:

答案 0 :(得分:1)

我想知道你的衍生进程是否阻止尝试编写其输出。来自Process的文档:

  

创建的子流程没有自己的终端或控制台。所有   它的标准io(即stdin,stdout,stderr)操作将是   通过三个流重定向到父进程   (getOutputStream(),getInputStream(),getErrorStream())。父母   进程使用这些流来输入和从中获取输出   子。因为某些本机平台仅提供有限的缓冲区   标准输入和输出流的大小,无法及时写入   输入流或读取子进程的输出流可能会导致   要阻止的子进程,甚至死锁

您应该在进程运行时使用进程'标准输出/错误,并且理想情况下在单独的线程中以避免阻塞。有关详细信息,请参阅this answer

相关问题