Java exec

Init

  1. Runtime.getRuntime() is the only method can get jvm runing environment
  2. Most method in Runtime is implements method
  3. Runtime.exit() is the only method exit current jvm. System.exit()
  4. 0 represent normal execute, !0 represent exception
  5. Runtime.addShutdownHook() can recieve a thread object as a handle
  6. public Process exec(String[] cmdarray, String[] envp, File dir)
    when sub process use current process environment variable, envp is null.

Call

1
2
Process proc = Runtime.getRuntime().exec("java");
int exitVal = proc.exitValue();

Process call exitValue is not block, if needed add a loop call

1
2
3
Process proc = Runtime.getRuntime().exec("java");
// add stream setting
int exitVal = proc.waitFor();

correct call process need set process’s stream setting, make sure thread will not block.

1
2
3
Process proc = Runtime.getRuntime().exec("java hello > hi");
// add stream setting
int exitVal = proc.waitFor();

in command line can’t execute bash sign like > >> < &.

1
2
3
4
Process proc = Runtime.getRuntime().exec(
new String[]{"/bin/bash", "-c", "java hello > hi"}, null, null);
// add stream setting
int exitVal = proc.waitFor();

if need these local operation, you can write these in a shell script, or load bash in java.

Call in windows

if you want call in windows you need install bash first

1
2
3
4
Process proc = Runtime.getRuntime().exec(
new String[]{"D:\\Program Files\\Git\\bin\\sh.exe", "-c", command}, null, null);
// add stream setting
int exitVal = proc.waitFor();

if jvm execute path is not the exec path, you need add specific path

1
2
3
4
Process proc = Runtime.getRuntime().exec(
new String[]{"D:\\Program Files\\Git\\bin\\sh.exe", "-c", command}, null, new File(workPath));
// add stream setting
int exitVal = proc.waitFor();

ps. -c mean read parameter in string format, not directly %0 %1

Another way

If you want jvm do standard in /out, use another thread read or write data

1
2
3
4
5
Process proc = Runtime.getRuntime().exec("java hello");
// add pip stream thread setting
StreamThread director = new StreamThread(proc.getInputStream(),proc.getOutputStream());
director.start();
int exitVal = proc.waitFor();

https://blog.csdn.net/mengxingyuanlove/article/details/50707746
https://blog.csdn.net/timo1160139211/article/details/75006938