1

I'm using Java exec to run bash script, but when I enter CTRL+C, the Java process will exit and also the sub processes, how can I keep child processes running after JVM is shut down?

String command = "ffmpeg -re -strict -2 -i video.mp4 -c:v copy -an -f rtp rtp://127.0.0.1:1234";
Utils.writeToFile("sub.sh", command);

new ProcessBuilder("parent.sh", "sub.sh").inheritIO()
        .start().waitFor();

parent.sh:

#!/bin/bash
trap '' SIGINT SIGTERM SIGQUIT SIGHUP SIGTSTP
nohup "$@" &

I have read answers to similar questions here and here, e.g, start a parent bash script in that script run command using nohup, or using trap command to prevent signals, on my research, it works for example "tail -f somefile", but not for my use case "ffmpeg -params", please help, thank you.

ArL
  • 283
  • 5
  • 11

1 Answers1

3

TL;DR

Use setsid instead of nohup in your parent.sh:

#!/bin/bash
setsid $@ &

The first problem is while your Java programm receives a SIGTERM signal (after CTRL + C), the JVM sends a SIGKILL signal to the child processes, which cannot be caught, blocked or ignored. So, once your parent.sh process receives SIGKILL, it's then passed to its child process sub.sh which stops the process.

The second problem is with nohup "$@" & you let your sub.sh child program run in background, but it is not completely detached from the current terminal. What nohup does is basically to ignore the SIGHUP signal. It executes the process normally (in the background) and doesn't actually provide daemonization.

Instead of nohup, you can use setsid, which detaches the child process sub.sh by creating a new session, which will then have no controlling terminal, and thus will no receive the SIGKILL signal.

One other way to do this might be using disown, like source $@ & disown, but in this case, it won't block the current terminal in which parent.sh is running. The problem is, you won't be able to know, when the child process is completed. So you would have more work to do, in order to monitor the child process id.

Further notes: