Huy Ngo
Huy Ngo

Reputation: 194

Why does java.lang.ProcessBuilder.start() starts a process by a fork()?

java.lang.ProcessBuilder.start() calls to java.lang.ProcessImpl.forkAndExec(), which is a native method. From what I learned in my Operating System class, a fork will basically create a clone of the process which called it. I have checked the PPID of processes created by ProcessBuilder.start() and confirmed that those PPIDs are equivalent to PID of current Java process.

However, ProcessBuilder.start() may run an arbitrarily process which share nothing with current Java process. So why does java.lang.ProcessBuilder.start() starts a new process by a fork()?

Upvotes: 0

Views: 181

Answers (1)

Stephen C
Stephen C

Reputation: 719446

Why does ProcessBuilder.start() starts a process by a fork()?

Because if it didn't fork() a child process, then the subsequent execve() would replace the JVM's code and data with the code and data of the new command you are running.

Why?

Because that is how the fork() and execve() system calls work.

Why?

Because:

  • it allows the child process (prior to the exec) to set up the file descriptors for that the exec'd command will see, and potentially other things
  • it was designed that way back in ~1970's era UNIX, and there hasn't been a strong enough case do it (significantly) differently.

Upvotes: 4

Related Questions