简体   繁体   中英

Java, inherit classpath with Runtime.exec()

I have a program that will create a child process, and I want it inherit all the classpath from its parent. In javadoc, it says:

public Process exec(String[] cmdarray, String[] envp) throws IOException

Executes the specified command and arguments in a separate process with the specified environment.

Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing "environment" variable settings, this method creates a new process in which to execute the specified command.

If envp is null, the subprocess inherits the environment settings of the current process.

When I set envp to null, it didn't inherit anything.

Here is the code:

System.out.print("Debug system path: "+System.getProperty("java.class.path"));
            startTime();
Process proc = Runtime.getRuntime().exec(cmd,null);

I can see the path information, but these path information is not inherited by the new created process.

How did you specify the classpath of your application? If it was not through the CLASSPATH environment variable, it will not be inherited.

Runtime.exec method can invoke any native application, and the envp here refers to system environment, not your java environment.

If you want to pass your classpath to the child java process, you can do so explicitly:

String[] cmdarray = new String[] {
  "java", "-classpath", System.getProperty("java.class.path"), "com.example.MyChildApp", "appParam"};

Process p = Runtime.getRuntime().exec(cmdarray);

No can do. Your 'classpath' at the time you call exec is whatever is hiding away in your current class loader at the time you call it. You can't, in general, ask a class loader to tell you the class path. It could be fetching classes from a database, or the planet Mars.

Reading java.class.path will tell you what was going on when your application started, but not what's going on at the time you go to launch something else.

Finally I have to insert "-cp System.getProperty("java.class.path")" into the cmd to make it work.

Is there any better way to do that?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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