To add a few points to the above answers:
- Starting the process in the background with '&' and wait for its pid as advised by @cuonglm will make it possible for the handler to execute while the child is running, but the child will loose the ability to catch any input as stdin will be closed as soon as the child is detached. To force stdin to stay open, you might add an infinite loop which you pipe to the child process. See this post.
Then read input in the current shell and write it to the proc file of the child's process so it goes to its stdin:
(while true; do sleep 10000; done) | /bin/start/main/server --nodaemon &
result=$(kill -0 $mypid > /dev/null 2>&1)
if [ $? -ne 0 ] ; then
# process is gone
# read input in the current shell and store it in a variable. The timeout only works with Bash, not with Bourne-Shell. You will need to find a way to read stdin instead and sleep 1 sec between each loop
read -t 1 input
# echo the input to the proc file of the runuser process so it goes to its stdin
echo $input > /proc/$child_pid/fd/0 2>/dev/null
NOTE: this works pretty well on Linux but might need some adjustments for other Unix platforms.
EDIT: a simpler method is to duplicate stdin to a file descriptor which can then be used as the stdin for the background process:
/bin/start/main/server --nodaemon <&3 &
exec is the second solution as suggested by @Stuart P. Bentley, but sometimes you need to create the process with a new PID or the command used might not let you the choice and create the process with a new PID or even a new PGID (that's the case for example for runuser with the -l option).
An alternative to 1) and 2) is to send the signal to the process group instead of targeting a specific PID.
This can be done by using kill with a minus (-) before the child's PID:
kill -TERM -$child_pid
Bash will indeed let you trap signals that are targeting a process group without needing to start the process in the background. This method will not loose the ability for the child process to read stdin. This is also a good solution if your child is running in a different process group as the handler will let you forward the signal to the child. Limitation is that other members of the group will also receive the signal, which might be a problem or not depending on the scenario.