Skip to content

Instantly share code, notes, and snippets.

@MarlikAlmighty
Created February 2, 2017 13:05
Show Gist options
  • Save MarlikAlmighty/7ea723924e8c4f51071b64073860b1c8 to your computer and use it in GitHub Desktop.
Save MarlikAlmighty/7ea723924e8c4f51071b64073860b1c8 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -w
use strict;
use warnings;
use POSIX;
use File::Pid;
# Имя демона
my $daemonName = "mydaemon";
# Используется в цикле для выхода
my $dieNow = 0;
# Путь к файлу PID, важно добавить свой путь куда есть доступ
my $pidFilePath = "/var/www/project/";
my $pidFile = $pidFilePath . $daemonName . ".pid";
# Демонизируем
use POSIX qw(setsid);
chdir '/';
umask 0;
open STDIN, '<', '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>', '/dev/null' or die "Can't write to /dev/null: $!";
open STDERR, '>', '/dev/null' or die "Can't write to /dev/null: $!";
defined(my $pid = fork) or die "Can't fork: $!";
exit if $pid;
POSIX::setsid() or die "Can't start a new session.";
local $SIG{INT} = local $SIG{TERM} = local $SIG{HUP} = \&signalHandler;
local $SIG{PIPE} = 'ignore';
my $pidfile = File::Pid->new({file => $pidFile,});
$pidfile->write or die "Can't write PID file, /dev/null: $!";
# Главный цикл, в нём ваш код
until ($dieNow)
{
# Ваш код
}
# Ловим сигнал для выхода
sub signalHandler
{
$dieNow = 1;
}
# Здесь пишем наши функции
# Выход, удаляем pid
END
{
$pidfile->remove if defined $pidfile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment