"Parent" Bash script
bash Child &
wait
sleep 5; echo "Main end" >>log.txt
"Child" script :
trap 'echo "Child end" >>log.txt;' ABRT
sleep 100
echo "Child end" >>log.txt
Run: bash Parent &
How to modify these scripts so that "kill -ABRT" would make Child exit with a trace in log.txt ?
As is, Child ignores such signals. It does if the first line (trap) is removed, but then, no trace is left in log.txt upon "kill -ABRT".
I don't know if I get your question, but can't you operate on PID? You can get it/print it out from variable $!.
bash child1 &; echo $!;
And then just kill -ABRT that_pid.
Or do you want to kill a process running a specific child script?
Related
i want to start programs in a chain, like start a bash script startScript.sh and then in the startScript.sh chain load certain programs.
startScript.sh
./program1 &
#PID=(echo $!)
PID=$!
echo "Wait for 10 seconds here"
if ps -p $PID > /dev/null; then echo "continue"; ./program2; else echo "PID is not running"; exit; fi
echo "Wait for 10 seconds here"
#if program1 is running and program2 is running, then ./program3, else exit.
I tried to find the running pid of program1 with $!, but the problem is that program1 is itself a shell script and they invokes further shell scripts in which I am not interested. Hence $! never gives me the pid of ./program1 but something irrelevant. HOw can I get the PID of program1?
Also how can I get the PID of program1 as well as program2 to see if they are running and then start program3.
The special parameter $! in shell (from man bash):
Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin (see JOB CONTROL below).
It's important to notice that job control is shell-local (in your case local to the bash interpreter executing your startScript.sh).
That means the pid from below:
#!/bin/bash
./program.sh
pid=$!
will always contain the PID of the program.sh script (i.e. the process executing it, defined with a hashbang, in your case probably another bash process), regardless of the background processes spawned by that child process (remember that $! is local to your script; the $! in the child will be undefined, until a background process is spawned there).
What maybe sidetracked you initially is the line:
PID=(echo $!)
that didn't properly set the PID. The PID was set to an array containing two words (elements): echo and <pid>. You want this:
pid=$!
(and maybe to use lowercase name for the non-global variable pid).
A simple demo:
$ cat script1.sh
#!/bin/bash
./script2.sh &
echo "in script1: $!"
$ cat script2.sh
#!/bin/bash
echo "in script2: $!"
sleep 5 &
echo "in script2 after sleep: $!"
$ ./script1.sh
in script1: 19537
in script2:
in script2 after sleep: 19541
Notice how the $! in initially undefined in script2.sh - if $! were to return the last PID globally, it would be set to PID of script2.sh.
This question already has answers here:
How do I kill background processes / jobs when my shell script exits?
(15 answers)
Closed 6 years ago.
I have scriptA which will execute another script which will startup in the background. Now I need to make sure that when I kill scriptA (cmd+c) that the background processes are also killed.
#!/bin/bash
echo "This script is about to run another script."
sh ../processes/processb/bin/startserver.sh &
FOO_PID=$!
echo "This script has just run another script." $FOO_PID
This script executes fine, but once I press cmd+c and do a 'ps' command on FOO_PID value , that process still exists. What am I doing wrong?
UPDATE-----------
So I tried out below code, but still scriptC's process is not getting killed. I think it just only terminates scriptA ( parent) when pressed ctrl+c and therefore trap command does not get executed?
#!/bin/bash
echo "This script is about to run another script."
../common/samples/bin/scriptC.sh &
mypid=$!
kill -0 "$mypid" && echo "My process is still alive."
echo "This script has just run another script." $mypid
trap "kill $mypid && kill $$" INT
Add a trap for SIGINT:
trap "kill $FOO_PID && kill $$" INT
or for any sort of exiting, handle the pseudo signal EXIT:
trap "kill $FOO_PID && kill $$" EXIT
I want to control a child script somehow. I am making a master script which spawns many children scripts and need to RESUME and PAUSE them on demand.
Child
Do stuff
PAUSE
Cleanup
Parent
sleep 10
RESUME child
Is this possible?
AS PER SUGGESTIONS
Trying to do it with signals while the child runs in the background doesn't seem to work.
script1:
#!/bin/bash
"./script2" &
sleep 1
kill -2 "$!"
sleep 1
script2:
#!/bin/bash
echo "~~ENTRY"
trap 'echo you hit ctrl-c, waking up...' SIGINT
trap 'echo you hit ctrl-\, stoppng...; exit' SIGQUIT
while [ 1 ]
do
echo "Waiting for signal.."
sleep 60000
echo "~~EXIT1"
done
echo "~~EXIT2"
Running:
> ./script1
One way to control individual process scripts is with signals. If you combine SIGINT (ctrl-c) to resume with SIGQUIT (ctrl-) to kill then the child process looks like this:
#!/bin/sh
trap 'echo you hit ctrl-c, waking up...' SIGINT
trap 'echo you hit ctrl-\, stoppng...; exit' SIGQUIT
while (true)
do
echo "do the work..."
# pause for a very long time...
sleep 600000
done
If you run this script, and hit ctrl-c, the work continues. If you hit ctrl-\, the script stops.
You would want to run this in the background then send kill -2 $pid to resume and kill -3 $pid to stop (or kill -9 would work) where $pid is the child process's process id.
Here is a good bash signals reference: http://www.ibm.com/developerworks/aix/library/au-usingtraps/
-- here is the parent script...
#!/bin/sh
./child.sh &
pid=$!
echo "child running at $pid"
sleep 2
echo "interrupt the child at $pid"
kill -INT $pid # you could also use SIGCONT
sleep 2
echo "kill the child at $pid"
kill -QUIT $pid
One way is to create a named pipe per child:
mkfifo pipe0
Then redirect stdin of the child to read from the pipe:
child < pipe0
to stop the child:
read _
(the odd _ is just there for read to have a place to store the empty line it will read).
to resume the child:
echo > pipe0
A more simple approach would be to save the stdin which gets passed to the child in form a pure file descriptor but I don't know the exact syntax anymore and can't google a good example ATM.
Is there any way to invoke a subprocess so that it and all its descendants are sent an interrupt, just as if you Ctrl-C a foreground task? I’m trying to kill a launcher script that invokes a long-running child. I’ve tried kill -SIGINT $child (which doesn’t send the interrupt to its descendants so is a no-op) and kill -SIGINT -$child (which works when invoked interactively but not when running in a script).
Here’s a test script. The long-running script is test.sh --child. When you call test.sh --parent, it invokes test.sh --child & and then tries to kill it. How can I make the parent kill the child successfully?
#!/bin/bash
if [ "$1" = "--child" ]; then
sleep 1000
elif [ "$1" = "--parent" ]; then
"$0" --child &
for child in $(jobs -p); do
echo kill -SIGINT "-$child" && kill -SIGINT "-$child"
done
wait $(jobs -p)
else
echo "Must be invoked with --child or --parent."
fi
I know that you can modify the long-running child to trap signals, send them to its subprocess, and then wait (from
Bash script kill background (grand)children on Ctrl+C), but is there any way without modifying the child script?
For anyone wondering, this is how you launch childs in the background and kill them on ctrl+c:
#!/usr/bin/env bash
command1 &
pid[0]=$!
command2 &
pid[1]=$!
trap "kill ${pid[0]} ${pid[1]}; exit 1" INT
wait
Read this : How to send a signal SIGINT from script to script ? BASH
Also from info bash
To facilitate the implementation of the user interface to job control,
the operating system maintains the notion of a current terminal process
group ID. Members of this process group (processes whose process group
ID is equal to the current terminal process group ID) receive keyboard-
generated signals such as SIGINT. These processes are said to be in
the foreground. Background processes are those whose process group ID
differs from the terminal's; such processes are immune to keyboard-gen‐
erated signals.
So bash differentiates background processes from foreground processes by the process group ID. If the process group id is equal to process id, then the process is a foreground process, and will terminate when it receives a SIGINT signal. Otherwise it will not terminate (unless it is trapped).
You can see the process group Id with
ps x -o "%p %r %y %x %c "
Thus, when you run a background process (with &) from within a script, it will ignore the SIGINT signal, unless it is trapped.
However, you can still kill the child process with other signals, such as SIGKILL, SIGTERM, etc.
For example, if you change your script to the following it will successfully kill the child process:
#!/bin/bash
if [ "$1" = "--child" ]; then
sleep 1000
elif [ "$1" = "--parent" ]; then
"$0" --child &
for child in $(jobs -p); do
echo kill "$child" && kill "$child"
done
wait $(jobs -p)
else
echo "Must be invoked with --child or --parent."
fi
Output:
$ ./test.sh --parent
kill 2187
./test.sh: line 10: 2187 Terminated "$0" --child
somecommand &
returns a pid of the child in $!
somecommand &
pid[0]=$!
anothercommand &
pid[1]=$!
trap "kill ${pid[0]} ${pid[1]}; exit 1" INT
wait
I would start with this model rather than with bash job control (bg, fg, jobs). Normally init inherits and reaps orphan processes. What problem are you trying to solve?
You can keep using SIGINT with background tasks with an easy little twist: Put your asynchronous subprocess call in a function or { }, and give it setsid so it has its own process group.
Here's your script keep it's whole first intention:
using and propagating SIGINT and not using another signal
modifying only the calling from: "$0" --child & to { setsid "$0" --child; } &
adding the code necessary to get the PID of your child instance, which is the only process in the background subshell.
Here's your code:
#!/bin/bash
if [ "$1" = "--child" ]; then
sleep 1000
elif [ "$1" = "--parent" ]; then
{ setsid "$0" --child; } &
subshell_pid=$!
pids=$(ps -ax -o ppid,pid --no-headers |
sed -r 's/^ +//g;s/ +/ /g' |
grep "^$subshell_pid " | cut -f 2 -d " ");
for child in $pids; do
echo kill -SIGINT "-$child" && kill -SIGINT "-$child"
done
wait $subshell_pid
else
echo "Must be invoked with --child or --parent."
Here's the important doc part from bash manual
Process group id effect on background process (in Job Control section of doc):
[...] processes whose process group ID is equal to the current terminal
process group ID [..] receive keyboard-generated signals such as
SIGINT. These processes are said to be in the foreground.
Background processes are those whose process group ID differs from
the terminal's; such processes are immune to keyboard-generated
signals.
Default handler for SIGINT and SIGQUIT (in Signals section of doc):
Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers.
and about modification of traps (in trap builtin doc):
Signals ignored upon entry to the shell cannot be trapped or reset.
I need to set a trap for a bash process I'm starting in the background. The background process may run very long and has its PID saved in a specific file.
Now I need to set a trap for that process, so if it terminates, the PID file will be deleted.
Is there a way I can do that?
EDIT #1
It looks like I was not precise enough with my description of the problem. I have full control over all the code, but the long running background process I have is this:
cat /dev/random >> myfile&
When I now add the trap at the beginning of the script this statement is in, $$ will be the PID of that bigger script not of this small background process I am starting here.
So how can I set traps for that background process specifically?
(./jobsworthy& echo $! > $pidfile; wait; rm -f $pidfile)&
disown
Add this to the beginning of your Bash script.
#!/bin/bash
trap 'rm "$pidfile"; exit' EXIT SIGQUIT SIGINT SIGSTOP SIGTERM ERR
pidfile=$(tempfile -p foo -s $$)
echo $$ > "$pidfile"
# from here, do your long running process
You can run your long running background process in an explicit subshell, as already shown by Petesh's answer, and set a trap inside this specific subshell to handle the exiting of your long running background process. The parent shell remains unaffected by this subshell trap.
(
trap '
trap - EXIT ERR
kill -0 ${!} 1>/dev/null 2>&1 && kill ${!}
rm -f pidfile.pid
exit
' EXIT QUIT INT STOP TERM ERR
# simulate background process
sleep 15 &
echo ${!} > pidfile.pid
wait
) &
disown
# remove background process by hand
# kill -TERM ${!}
You do not need trap to just run some command after a background process terminates, you can instead run through a shell command line and add the command following after the background process, separated with semicolon (and let this shell run in the background instead of the background process).
If you still would like to have some notification in your shell script send and trap SIGUSR2 for instance:
#!/bin/sh
BACKGROUND_PROCESS=xterm # for my testing, replace with what you have
sh -c "$BACKGROUND_PROCESS; rm -f the_pid_file; kill -USR2 $$" &
trap "echo $BACKGROUND_PROCESS ended" USR2
while sleep 1
do
echo -n .
done