import java.lang.ProcessBuilder.Redirect;
public class Main {
public static void main(String args[]){
ProcessBuilder pb = new ProcessBuilder(args);
try{
Process p = pb.start();
System.out.println("child process is alive: " + p.isAlive());
System.out.println("child process pid: " + p.pid());
System.out.println("parent of child process: " + p.toHandle().parent().get().pid());
System.out.println("child process is alive: " + p.isAlive());
p.waitFor();
} catch (Exception e) {
System.out.println("some exception with start process.");
e.printStackTrace();
}
}
}
on Ubuntu 18.04, I run the program to run an external program sleep 10
without problme:
$ java Main sleep 10
child process is alive: true
child process pid: 20559
parent of child process: 20539
child process is alive: true
$
But when I run the program to run an external program echo hello
$ java Main echo hello
child process is alive: false
child process pid: 18534
some exception with start process.
java.util.NoSuchElementException: No value present
at java.base/java.util.Optional.get(Optional.java:148)
at Main.main(Main.java:11)
Why does it report error at get()
in line 11 p.toHandle().parent().get().pid()
?
If I comment out line 11, it will run without problem. Why is that?
If it is because the child exits before calling p.toHandle().parent().get().pid()
at line 11,
- why does
NoSuchElementException
happen atget()
instead of earlier attoHandle()
or atparent()
inp.toHandle().parent().get().pid()
at line 11? - Why is there no such problem when calling
p.pid()
at line 10?
What can I do to make the problem not happen? For example, how can I make the child last longer, so that p.toHandle().parent().get().pid()
can work, even when I run a short lived program in the child process?