【问题标题】:Runtime.exec() doesn't work correct on tomcat / web applicationRuntime.exec() 在 tomcat / Web 应用程序上无法正常工作
【发布时间】:2012-03-05 17:45:57
【问题描述】:

在我的 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

“Web 应用程序模式”下的输出(错误):

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

或者当我删除 getEnvirement 代码时(也不好):

before getEnvirement
before new Application

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

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

【问题讨论】:

    标签: java web-applications tomcat


    【解决方案1】:

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

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

    您应该在进程运行时使用进程的标准输出/错误,最好在单独的线程中使用以避免阻塞。请参阅this answer 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      相关资源
      最近更新 更多