简体   繁体   English

当java作为服务运行时从java启动进程

[英]start process from java when java run as service

I have a java process running as windows server using prcorun ( http://commons.apache.org/proper/commons-daemon/ ); 我有一个使用prcorun作为Windows服务器运行的java进程( http://commons.apache.org/proper/commons-daemon/ ); unfortunatly I have to launch an external legacy command written in C/C++. 不幸的是,我必须启动一个用C / C ++编写的外部遗留命令。

both

Process myProcess = Runtime.getRuntime().exec(command);

and

Process myProcess = new ProcessBuilder(command, arg).start();

work well when java is launched as a stand-alone application, but when I start java as service it replies 当java作为一个独立的应用程序启动时运行良好,但当我启动java作为服务时,它会回复

command not found

also with 还有

Process myProcess = Runtime.getRuntime().exec("dir");

command not found

I think is a problem due to windows services. 我认为是由于Windows服务导致的问题。

Any suggestion? 有什么建议吗?

I would try to do a quick test and print the PATH environment variable in your service. 我会尝试快速测试并在您的服务中打印PATH环境变量。 What I usually found when you run some command as a service, the PATH might not be totally available (which can also explain why DIR is not working for you). 当您将某个命令作为服务运行时,我通常会发现,PATH可能不完全可用(这也可以解释为什么DIR不适合您)。 If that the case, when starting the service, you have to make sure the PATH include both the normal bin and your legacy bin. 如果是这种情况,在启动服务时,您必须确保PATH包含普通bin和旧bin。

As the error says, the command is not found in the path. 如错误所示,在路径中找不到该命令。 You'll need to set the environment variable PATH to the child process's environment. 您需要将环境变量PATH设置为子进程的环境。 Look at exec(cmd, String[] env) method. 看一下exec(cmd,String [] env)方法。 You can create an array of environment variables (key value pairs) and pass it to exec(). 您可以创建一个环境变量数组(键值对)并将其传递给exec()。

In my case I used 在我的情况下,我用过

cmd /c <<YOUR COMMAND>>

eg. 例如。 Process myProcess = Runtime.getRuntime().exec("cmd /c dir"); 处理myProcess = Runtime.getRuntime()。exec(“cmd / c dir”);

also I added the envinronments. 我还添加了envinronments。 as suggested by smurf 正如smurf所说

private static String[] getEnv() {
    Map<String, String> env = System.getenv();
    String[] envp = new String[env.size()];
    int i = 0;
    for (Map.Entry<String, String> e : env.entrySet()) {
        envp[i++] = e.getKey() + "=" + e.getValue();
    }
    return envp;
}

... ...

Process myProcess = Runtime.getRuntime().exec("cmd /c dir",getEnv());

Alternative to java.lang.Runtime.exec() that can execute command lines as a single string? java.lang.Runtime.exec()的替代方法,可以将命令行作为单个字符串执行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM