<p>The <code>bitcoind</code> process exits almost immediately when you run <code>bitcoind-cli stop</code> so you cannot simply detect the <code>bitcoind</code> process. <em>Even though you can possibly see <code>bitcoind</code> with <code>htop</code> after running <code>bitcoin-cli stop</code> you cannot see it with <code>ps</code> because it has exited.</em></p>
<p>The answer is to find a way to reliably wait for the process cache to finish writing to disk. <code>bitcoind</code> nicely writes to debug log with the following message as the last thing it sends to disk, <code>Shutdown: done</code> so it is possible to detect this way.</p>
<p>The following script is available on <a href="https://github.com/Willtech/bitcoin-script/blob/master/runbitcoind.sh" rel="nofollow noreferrer">GitHub</a> on the <a href="https://github.com/Willtech/bitcoin-script/blob/master/LICENSE" rel="nofollow noreferrer">MIT Licence</a> and is republished here with permission under the additional licences of.</p>
<p>I Hope it is useful for you.</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
# Exit and restart bitcoind after some time period
# Willtech ©2022

# How often to restart in seconds
timeout=3600

# BAT / CMD goto function
# Source: https://www.codegrepper.com/code-examples/shell/bash+jump+to
function goto
{
    label=$1
    cmd=$(sed -n &quot;/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};&quot; $0 | 
          grep -v ':$')
    eval &quot;$cmd&quot;
    exit
}
# Just for the heck of it: how to create a variable where to jump to:
start=${1:-&quot;start&quot;}
goto &quot;$start&quot;

: start

#Start bitcoind
bitcoind -daemon

#Run until timout
sleep $timeout

#Stop bitcoind
bitcoin-cli stop

#Tries for ten minutes to see if exit is detected.
until timeout 600s tail -f /media/drive2/.bitcoin/debug.log | grep -m 1 &quot;Shutdown: done&quot;
  do
    sleep 2
  done

#Log again
echo again

#Loop to : start
goto &quot;start&quot;

echo bar

# Ref &gt;&gt;&gt;
## https://askubuntu.com/a/1070296
## https://www.delftstack.com/howto/linux/bash-goto/
</code></pre>
<p>Anecdotally, it used to take maybe a month with 1TB USB3 platter disk to do initial sync even with swap as larger than 100GB but now it takes only about three days restarting every one hour until it is up to date. That is in blocks download mode on a blank disk so that data is written near to where it is found.</p>

CC BY-SA 4.0
2022-02-26T03:48:01.653Z
Note you need to set your location of `debug.log`.
Willtech
CC BY-SA 4.0
2022-02-26T03:46:51.593Z
2024-02-26T12:16:09.610Z
2024-02-26T12:16:09.610Z
Willtech
<p>If, like me you wish to automatically restart bitcoind after some period of time, or if it crashes at least it will restart sometime on it's own you know that it can take a long time on Linux before process cache finishes writing to disk and then you can restart without the dreaded message <code>Error: Cannot obtain a lock on data directory /media/drive2/.bitcoin/. Bitcoin Core is probably already running.</code></p>
<p>How to restart bitcoind automatically using a script without error message and failure to start?</p>
<p>This question is specifically to allow <code>bitcoind</code> to exit cleanly as it can take an inordinate amount of time to exit cleanly even though you cannot see the process with <code>ps -ae | grep bitcoind</code> you can still see it with <code>htop</code> until it finishes committing the process cache to disk and finally &quot;Shutdown: done&quot; is written to disk. If configured as  daemon it is possible to have thousands of failures starting before the process finally exists.</p>

CC BY-SA 4.0
2022-02-26T18:15:04.773Z
Does this answer your question? [Ubuntu Linux -- How do I start bitcoind as a service to run automatically?](https://bitcoin.stackexchange.com/questions/13795/ubuntu-linux-how-do-i-start-bitcoind-as-a-service-to-run-automatically)
RedGrittyBrick
CC BY-SA 4.0
2022-03-04T12:01:15.513Z
@RedGrittyBrick It would be part answer but it does not safely exit and then restart the process like a process cache flush.
Willtech
CC BY-SA 4.0
2022-03-11T15:03:24.213Z
Actually I have not checked, I presume that if I configure `bitcoind` as a service and run `systemctl stop bitcoind.service` that it returns immediately?
Willtech
CC BY-SA 4.0
2022-03-11T15:08:39.730Z
The operating system has features designed to do what you want, specifically the `respawn`  or [`restart`](https://ma.ttias.be/auto-restart-crashed-service-systemd/)`directive is intended to ensure that a service which dies gets restarted ASAP. Where this can be used I think it is often likely to be better than a homebrew solution as probably more time has been spent on the feature by a greater number of people over a much longer period in which bugs and wrinkles have been ironed out.
RedGrittyBrick
CC BY-SA 4.0
2022-03-11T15:30:19.293Z
@RedGrittyBrick Oh I agree it is just if `systemd` understands the difference between exiting clearing application cache and process exited. Let me know if you check I can update my answer.
Willtech
<bitcoind><script><bash>
How to regularly restart bitcoind after some period of time on Linux
Willtech
# How to regularly restart bitcoind after some period of time on Linux

(Asked by: username_0 on 2022-02-26)

If, like me you wish to automatically restart bitcoind after some period of time, or if it crashes at least it will restart sometime on it's own you know that it can take a long time on Linux before process cache finishes writing to disk and then you can restart without the dreaded message `Error: Cannot obtain a lock on data directory /media/drive2/.bitcoin/. Bitcoin Core is probably already running.`

How to restart bitcoind automatically using a script without error message and failure to start?

This question is specifically to allow `bitcoind` to exit cleanly as it can take an inordinate amount of time to exit cleanly even though you cannot see the process with `ps -ae | grep bitcoind` you can still see it with `htop` until it finishes committing the process cache to disk and finally "Shutdown: done" is written to disk. If configured as daemon it is possible to have thousands of failures starting before the process finally exists.

**Tags:** bitcoind, script, bash

> **Comments:**
> **username_1**: Does this answer your question? [Ubuntu Linux -- How do I start bitcoind as a service to run automatically?](https://bitcoin.stackexchange.com/questions/13795/ubuntu-linux-how-do-i-start-bitcoind-as-a-service-to-run-automatically)  
> **username_0**: @username_1 It would be part answer but it does not safely exit and then restart the process like a process cache flush.  
> **username_0**: Actually I have not checked, I presume that if I configure `bitcoind` as a service and run `systemctl stop bitcoind.service` that it returns immediately?  
> **username_1**: The operating system has features designed to do what you want, specifically the `respawn`  or [`restart`](https://ma.ttias.be/auto-restart-crashed-service-systemd/)`directive is intended to ensure that a service which dies gets restarted ASAP. Where this can be used I think it is often likely to be better than a homebrew solution as probably more time has been spent on the feature by a greater number of people over a much longer period in which bugs and wrinkles have been ironed out.  
> **username_0**: @username_1 Oh I agree it is just if `systemd` understands the difference between exiting clearing application cache and process exited. Let me know if you check I can update my answer.  

---

## 1 answers

### Answer by username_0 on 2022-02-26. Score: 2 | Accepted answer

The `bitcoind` process exits almost immediately when you run `bitcoind-cli stop` so you cannot simply detect the `bitcoind` process. *Even though you can possibly see `bitcoind` with `htop` after running `bitcoin-cli stop` you cannot see it with `ps` because it has exited.*

The answer is to find a way to reliably wait for the process cache to finish writing to disk. `bitcoind` nicely writes to debug log with the following message as the last thing it sends to disk, `Shutdown: done` so it is possible to detect this way.

The following script is available on [GitHub](https://github.com/username_0/bitcoin-script/blob/master/runbitcoind.sh) on the [MIT Licence](https://github.com/username_0/bitcoin-script/blob/master/LICENSE) and is republished here with permission under the additional licences of.

I Hope it is useful for you.

```bash
#!/bin/bash
# Exit and restart bitcoind after some time period
# username_0 ©2022

# How often to restart in seconds
timeout=3600

# BAT / CMD goto function
# Source: https://www.codegrepper.com/code-examples/shell/bash+jump+to
function goto
{
    label=$1
    cmd=$(sed -n "/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};" $0 | 
          grep -v ':$')
    eval "$cmd"
    exit
}
# Just for the heck of it: how to create a variable where to jump to:
start=${1:-"start"}
goto "$start"

: start

#Start bitcoind
bitcoind -daemon

#Run until timout
sleep $timeout

#Stop bitcoind
bitcoin-cli stop

#Tries for ten minutes to see if exit is detected.
until timeout 600s tail -f /media/drive2/.bitcoin/debug.log | grep -m 1 "Shutdown: done"
  do
    sleep 2
  done

#Log again
echo again

#Loop to : start
goto "start"

echo bar

# Ref >>>
## https://askubuntu.com/a/1070296
## https://www.delftstack.com/howto/linux/bash-goto/

```

Anecdotally, it used to take maybe a month with 1TB USB3 platter disk to do initial sync even with swap as larger than 100GB but now it takes only about three days restarting every one hour until it is up to date. That is in blocks download mode on a blank disk so that data is written near to where it is found.

> **Comments:**
> **username_0**: Note you need to set your location of `debug.log`.  

---

