How do I daemonize an arbitrary script in unix?

后端 未结 12 968
陌清茗
陌清茗 2020-11-30 16:33

I\'d like a daemonizer that can turn an arbitrary, generic script or command into a daemon.

There are two common cases I\'d like to deal with:

  1. I hav

12条回答
  •  星月不相逢
    2020-11-30 17:11

    This is a working version complete with an example which you can copy into an empty directory and try out (after installing the CPAN dependencies, which are Getopt::Long, File::Spec, File::Pid, and IPC::System::Simple -- all pretty standard and are highly recommended for any hacker: you can install them all at once with cpan ...).


    keepAlive.pl:

    #!/usr/bin/perl
    
    # Usage:
    # 1. put this in your crontab, to run every minute:
    #     keepAlive.pl --pidfile= --command= 
    # 2. put this code somewhere near the beginning of your script,
    #    where $pidfile is the same value as used in the cron job above:
    #     use File::Pid;
    #     File::Pid->new({file => $pidfile})->write;
    
    # if you want to stop your program from restarting, you must first disable the
    # cron job, then manually stop your script. There is no need to clean up the
    # pidfile; it will be cleaned up automatically when you next call
    # keepAlive.pl.
    
    use strict;
    use warnings;
    
    use Getopt::Long;
    use File::Spec;
    use File::Pid;
    use IPC::System::Simple qw(system);
    
    my ($pid_file, $command);
    GetOptions("pidfile=s"   => \$pid_file,
               "command=s"   => \$command)
        or print "Usage: $0 --pidfile= --command= \n", exit;
    
    my @arguments = @ARGV;
    
    # check if process is still running
    my $pid_obj = File::Pid->new({file => $pid_file});
    
    if ($pid_obj->running())
    {
        # process is still running; nothing to do!
        exit 0;
    }
    
    # no? restart it
    print "Pid " . $pid_obj->pid . " no longer running; restarting $command @arguments\n";
    
    system($command, @arguments);
    

    example.pl:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::Pid;
    File::Pid->new({file => "pidfile"})->write;
    
    print "$0 got arguments: @ARGV\n";
    

    Now you can invoke the example above with: ./keepAlive.pl --pidfile=pidfile --command=./example.pl 1 2 3 and the file pidfile will be created, and you will see the output:

    Pid  no longer running; restarting ./example.pl 1 2 3
    ./example.pl got arguments: 1 2 3
    

提交回复
热议问题