Skip to content

Instantly share code, notes, and snippets.

@marshyon
Created November 4, 2015 11:16
Show Gist options
  • Save marshyon/c49c9ecb1ffcbaaaa085 to your computer and use it in GitHub Desktop.
Save marshyon/c49c9ecb1ffcbaaaa085 to your computer and use it in GitHub Desktop.
Ubuntu Upstart service plus simple Perl script
description "sleepy server"
start on runlevel [2345]
stop on runlevel [!2345]
# set up an environment variable
env TIME=inf
# restart this process if it dies
respawn
# disable console
console none
# do any pre start stuff to set up for process to run ok
pre-start script
#test -x /usr/sbin/sshd || { stop; exit 0; }
#test -e /etc/ssh/sshd_not_to_be_run && { stop; exit 0; }
#mkdir -p -m0755 /var/run/sshd
end script
exec /usr/local/bin/sleeping_app.pl $TIME
#!/usr/bin/env perl
use File::Pid;
my $pidfile = "/var/run/sleeping_app.pid";
$SIG{TERM} = sub { unlink($pidfile); exit; };
$SIG{INT} = sub { unlink($pidfile); exit; };
die "there is already a $0 process running\n" if ( -e $pidfile );
my $pf = File::Pid->new({
file => $pidfile
});
$pf->write;
while(1) {
sleep 10;
}
@marshyon
Copy link
Author

marshyon commented Nov 4, 2015

This is a trivial Perl script that can be managed on an Ubuntu or Ubuntu like system with 'upstart' :

http://upstart.ubuntu.com/wiki/Documentation/WritingAService

to see if the service is running, after creating the /etc/iniit/sleep file,

# initctl list | grep sleep
sleep start/running, process 6615

the 'service' can be stopped / started with

# stop sleep
sleep stop/waiting

# ps -ef |grep sleeping | grep -v grep
#

# start sleep
sleep start/running, process 7614
# ps -ef |grep sleeping | grep -v grep
root      7614     1  0 11:19 ?        00:00:00 perl /usr/local/bin/sleeping_app.pl inf

If the process is killed, respawn will restart the process. Here the pid '7614', from the above ps command is killed,

# kill 7614
# ps -ef |grep sleeping | grep -v grep
root      7628     1  1 11:23 ?        00:00:00 perl /usr/local/bin/sleeping_app.pl inf

and immediately after the process is running again

The sleeping Perl app does nothing, it just 'sleeps' but ofcourse can be modified, adding things that need to be done before or after the 'sleep' command, for example :

while(1) {
  system("/usr/local/bin/run_very_importan_process");
  sleep 1;
} 

The section in the upstart 'sleep' file under 'pre-start script' is commented out but left for reference. It is where things can be done to check if the script to be run exists, if directories are present etc. It is left for this to be edited as appropriate or to be deleted if not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment