Hi,

I am using dspam running as a daemon, and here is a simple init script
for it :) 

Hope it is useful.

#!/usr/bin/perl -w
use strict;
use POSIX qw/setsid/;


my $cmd = shift;
my $pid = "/home/dspam/var/dspam.pid";
die "Usage: $0 start|stop|restart\n" unless $cmd and $cmd =~ 
/^start|stop|restart$/;

if ($cmd =~ /^start/) {
    start();
    exit 0;
}
if ($cmd =~ /^stop/) {
    stop();
    exit 0;
}
if ($cmd =~ /^restart/) {
    stop();
    sleep 1;
    start();
    exit 0;
}

sub check {
    if (-f $pid) {
        open FD, "< $pid" or die "cannot open pid file $pid: $!\n";
        my $id = <FD>;
        close FD;
        chomp $id;

        if (kill 0 => $id) {
            return $id;
        }
    }
    0;
}

sub stop {
    if (my $id = check()) {
        print "stop dspam daemon ...";
        kill 9 => $id;
        succ();
    } else {
        print "dspam is not running ...";
        fail();
        exit 1;
    }
}

sub start {
    if (!check()) {
        print "start dspam daemon ...";
        daemonize();
        exec("sudo -u vuser /home/dspam/bin/dspam --daemon");
        exit 0;
    } else {
        print "dspam is still runing ...";
        fail();
        exit 1;
    }
}

sub daemonize {
    my($pid, $sess_id, $i);

    if ($pid = fork) { exit 0; }

    die("Cannot detach from controlling terminal") unless $sess_id = 
POSIX::setsid();

    $SIG{'HUP'} = 'IGNORE';
    if ($pid = fork) { succ(); exit 0; }

    chdir "/";

    umask 0;

    close(STDIN);
    close(STDOUT);
    close(STDERR);

    ## Reopen stderr, stdout, stdin to /dev/null
    open(STDIN,  "+>/dev/null");
    open(STDOUT, "+>&STDIN");
    open(STDERR, "+>&STDIN");
}

sub succ {
    print "\e[60G[\e[1;32m  OK  \e[0;39m]\n";
}

sub fail {
    print "\e[60G[\e[1;31mFAILED\e[0;39m]\n";
}


-- 
Xueron Nee <[EMAIL PROTECTED]>

Reply via email to