1
I'm writing a bash script for some Bitcoin / Lightning experiments. I want to start bitcoind in the background (and also LN instances, but they are not the focus of this question). I want the script to shutdown bitcoind gracefully and exit on Ctrl+C. This is my attempt to implement this:
#!/bin/bash
echo "Starting bitcoind in the background..."
bitcoind &
sleep 5
echo "bitcoind started."
BITCOIND_PID=$!
echo $BITCOIND_PID
cleanup() {
echo 'cleaning up'
pkill $BITCOIND_PID
exit
}
trap "cleanup" INT
# Run the script until we stop it
wait
This script produces the following output:
<some bitcoind output>
bitcoind started.
18574
2019-09-17T14:12:20Z Adding fixed seed nodes as DNS doesn't seem to be available.
^C2019-09-17T14:14:07Z tor: Thread interrupt
cleaning up
2019-09-17T14:14:07Z opencon thread exit
2019-09-17T14:14:07Z torcontrol thread exit
2019-09-17T14:14:07Z addcon thread exit
2019-09-17T14:14:07Z Shutdown: In progress...
2019-09-17T14:14:07Z net thread exit
sergei:~$ 2019-09-17T14:14:07Z msghand thread exit
2019-09-17T14:14:07Z scheduler thread interrupt
2019-09-17T14:14:07Z Dumped mempool: 2e-06s to copy, 0.004053s to dump
2019-09-17T14:14:07Z [default wallet] Releasing wallet
2019-09-17T14:14:07Z Shutdown: done
Then I have to press Ctrl+C once again to exit the script.
How do I make the script shutdown bitcoind first and then exit automatically?
Related: How to use Ctrl+C to kill all background processes started in a Bash script?, Best way to kill processes created by bash script?.
I replaced 'pkill $BITCOIND_PID
withbitcoin-cli stop; sleep 2. Now I have: ```^C2019-09-18T09:23:50Z tor: Thread interrupt 2019-09-18T09:23:50Z Shutdown: In progress... cleaning up <...> error: Could not connect to the server 127.0.0.1:18443 <...> 2019-09-18T09:23:50Z Shutdown: done``` which probably means the stop signal is sent to bitcoind two times: "directly" and through my trap. So whenbitcoin-cliis called,bitcoindis already stopped. How can I preventbitcoindfrom exiting before I callbitcoin-cli stop`? – Sergei Tikhomirov – 2019-09-18T09:25:31.130I see the same behaviour here, with differences I attribute to testing on 0.13.2. It might not be the stop signal being sent twice - it could be an attempt to discern if the initial shutdown was successful. – Alistair Mann – 2019-09-18T12:32:55.880