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?.

Sergei Tikhomirov
  • 1,430
  • 7
  • 17

1 Answers1

2

Is bitcoin-cli available? If so, bitcoin-cli stop instead of pkill $BITCOIND_PID.

My own preference is to add sleep 2 following a stop, as I've experienced issues immediately restarting the stopped daemon where it behaves like a child thread hasn't finished cleaning up before the parent exits. That may not be what's happening - I've not investigated that behaviour.

Alistair Mann
  • 662
  • 3
  • 13
  • I replaced 'pkill $BITCOIND_PID` with `bitcoin-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 when `bitcoin-cli` is called, `bitcoind` is already stopped. How can I prevent `bitcoind` from exiting before I call `bitcoin-cli stop`? – Sergei Tikhomirov Sep 18 '19 at 09:25
  • I 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 Sep 18 '19 at 12:32