Why does killing the JVM also terminate the child process if waitFor was used?

If waitFornot used, killing the JVM does not affect its child process. Here is an example.

Bash script:

#!/usr/bin/env bash
echo "Sleeping..." > 'log'
sleep 30
echo "Wake up" >> 'log'

Java Code:

public class Code {
  public static void main(String[] args) throws Exception {
    Process process = Runtime.getRuntime().exec("./child.sh");
    // process.waitFor();
  }
}

Upon release, the Java CodeJVM terminates immediately. And ps -ef | grep 'child.sh' | grep -v grepshows:

jing      3535  2761  0 13:47 pts/15   00:00:00 bash ./child.sh

Then after 30 seconds I will check the contents of the logfile in the current directory. Content:

Sleeping...
Wake up

grep . process.waitFor() Code.java. Java Code grep, , child.sh. Ctrl-C, JVM . grep . log :

Sleeping...

Process Javadoc, . fork, execlp waitpid. .

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

static void err_sys(const char* msg) {
  printf("%s\n", msg);
  exit(1);
}

int main(void) {
    pid_t   pid;

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) {
        if (execlp("/home/jing/code/lintcode/child.sh", "child.sh", (char *)0) < 0)
            err_sys("execlp error");
    }

  if (waitpid(pid, NULL, 0) < 0)
    err_sys("wait error");

  exit(0);
}

Oracle JDK 1.8 Ubuntu 14.04. uname -a :

Linux jinglin 3.13.0-108-generic #155-Ubuntu SMP Wed Jan 11 16:58:52 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

- waitFor waitpid?

Does Process.waitFor() java? MAC. . .

+4
1

waitPid(), , .


fork, , () :

─┬= 1 init
 └─┬= 2 bash --login
   └─┬= 3 java code
     └─── 4 bash child.sh

java - , .

^ C, . 1


, , . java , .

─┬= 1 init
 ├──= 2 bash --login
 └─── 4 bash child.sh

.


1 SIGINT, . .

+3

Source: https://habr.com/ru/post/1669343/


All Articles