whenever the inet goes down, do something, wait until inet recovers, then restart program x.

hostnamectl; # tested on
Operating System: Debian GNU/Linux 12 (bookworm) 
Kernel: Linux 6.1.0-20-amd64
Architecture: x86-64

ping -V
ping from iputils 20221126
libcap: yes, IDN: yes, NLS: no, error.h: yes, getrandom(): yes, __fpending(): yes

ping -c1 1.1.1.1 ; echo $?
# 0 <- works

# disconnect from inet
ping –c1 1 1.1.1.1 ; echo $?
# 1 <- 0% replies

ping –c1 1 192.168.1.5 0; echo $?
# 2 <- other error

ping manpage:

  • If ping does not receive any reply packets at all it will exit with code 1
    • If a packet count and deadline are both specified, and fewer than count packets are received by the
      time the deadline has arrived, it will also exit with code 1
  • On other errors it exits with code 2
  • Otherwise it exits with code 0
vim /scripts/inet_monitor_restart_program_if_down.sh
#!/bin/bash

# server to used for testing if online
SERVER="1.1.1.1"

# set program to kill and restart when int goes down
PROGRAM_TO_RESTART="pluma"

# start the program once at start of script
$PROGRAM_TO_RESTART &

# Function to check internet connection
check_internet()
{
   ping -c 1 $SERVER|grep received
   # if less live output is wanted change to
   # ping -c 1 $SERVER > /dev/null 2>&1
   return $?
}

# Main loop
while true; do
# Check internet connection
if ! check_internet; then
   killall $PROGRAM_TO_RESTART > /dev/null 2>&1
   while true; do
   if check_internet
   then
      echo "inet recovered, restarting program $PROGRAM_TO_RESTART"
      killall $PROGRAM_TO_RESTART > /dev/null 2>&1
      sleep 1
      $PROGRAM_TO_RESTART &
      break;
   else
      echo "inet is down, killing $PROGRAM_TO_RESTART... and waiting for inet to recover"
      sleep 1
   fi
   done
else
   echo "...inet is up do nothing"
fi
sleep 1
done

liked this article?

  • only together we can create a truly free world
  • plz support dwaves to keep it up & running!
  • (yes the info on the internet is (mostly) free but beer is still not free (still have to work on that))
  • really really hate advertisement
  • contribute: whenever a solution was found, blog about it for others to find!
  • talk about, recommend & link to this blog and articles
  • thanks to all who contribute!
admin