Processes receive signals from other processes or kernel as a warning or as a request to make some change in state. Receiving processes can block, ignore or catch signals, except
SIGKILL which does what the name says. A process receives
SIGHUP (hangup signal) when its controlling terminal (virtual or pseudo) disconnects or its controlling process (which is usually a shell) terminates. Quoted from
adb shell source:
PTYs automatically send SIGHUP to the slave-side process when the master side of the PTY closes
* See Terminals and Shells on Android for details on PTYs
Process can then handle the signal to continue its execution or just gets killed by the kernel.
nohup makes a process run (usually in background) by simply ignoring
SIGHUP even if the controlling terminal closes. Additionally if FDs
2 of the process are attached to the terminal,
/system/bin/nohup has some bad implementation like many other applets of
toybox. It replaces
STDIN with nothing and leaves
STDERR attached to the terminal. So all shell commandline tools which are related to
system_server behave unexpectedly because of no FD
Solution is to use
nohup e.g. from busybox or do:
nohup tether.sh </dev/null &
tether.sh </dev/null &>/sdcard/usb.log &
In order to make sure a program ignores
trap '' 1 to script above the program to be executed. But it's not required with Android's default MirBSD Korn Shell (
/system/bin/sh) which doesn't send
SIGHUP to all jobs (children processes) in the same session i.e. attached to the same terminal. So
trap isn't essentially required, whether shell exits or gets killed.
mksh doesn't detach from terminal(s) completely because in addition to
STDIN/OUT/ERR, it attaches to
/dev/tty directly (ref). So detaching FDs
0/1/2 doesn't suffice. However there's a daemon mode which completely detaches the command from terminal:
/system/bin/sh -T- tether.sh
mksh unblocks all signals, though not relevant here.
bash provides better job management; user can configure with
huponexit whether or not to always send
SIGHUP to all jobs on exit (ref). Bash's built-in
disown command can be used to exclude jobs from receiving signals.
To keep script running in foreground, a multiplexer like
screen can be used. That's what I do, particularly with
su binaries from rooting solutions which don't detach (due to limited implementation of pseudo-terminals), when a program is running in background. See this issue for details.
RELATED: How to run an executable on boot and keep it running?