How to start Script as Daemon – DEBIAN – UBUNTU
########################################

Note this is from this article: http://xmodulo.com/2013/01/how-to-automatically-start-program-on-boot-in-debian.html

Note: didnt test in latest Ubuntu but should work

This is how you can start a script or a service on boot and turn it off on shutdown.

NOTE: All scripts below should use full paths, or variables that point to full path
NOTE: if you get LSB warning when doing update-rc.d foobar defaults, realize its just a warning
NOTE: use /bin/sh not /bin/bash in the service script (although im sure bash is fine), its just I checked thru all of my /etc/init.d service files on my debian system and out 60 scripts, 2 used #!/bin/bash and 58 used #!/bin/sh

NOTE: read the comments to learn some good etiquette
NOTE: generally the comments in init files have a format followed that should look something like this but we are skipping it (its explained in depth in /etc/init.d/README):

PROGRAM THAT RUNS QUICK
=========================

This is for programs that run once and quick like “date”. The point is that it runs once.

Note: service script start
Will start everything as child of sysvinitd so it will not be tied to shell (it will bel ike starting program with nohup) so that you can close shell and program still runs

If starting that runs once on boot:

Be root

Now to start the service you can

Or

So make it executable like so

To ensure this runs on start up (in systemd terms, to enable service):

To remove it from starting up (in systemd terms, to disable service):

PROGRAM THAT RUN FOREVER
=========================

Programs that run forever like daemons or services. Or a looping script.
I have a looping script that checks if cron is running. And if cron dies, it restarts it.

My cron script to monitor cron and turn it on if its dead (it just turn it on every 5 seconds, but if you start cron thru services cron wont start again if its running)

My service file:

To enable it (so it turn on during boot up):

To enable it (so it doesnt turn on during boot up):

NOTE:
If I started my script like so:

It will die when I turn off shell/terminal/putty session

If I started my script like so:

It wants me to press annoyingly
With # pstree it will look like its tied to bash, but when you turn off the terminal it will quickly become a child of PID 1 (init), thus persistenting closing shells

If I started service like so

It will also die when I turn off my shell/terminal/putty
You can check with  # pstree You will see its tied to bash

However If I started service like so:

Then it will be tied to PID1 (init process) and thus persist thru closing of shells and terminal. It will always be alive untill I kill it or close it with  service monitor-cron stop With # pstree you will see its tied to PID 1

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *