What's the best way to make sure only one instance of a Perl program is running?

后端 未结 3 1112
清歌不尽
清歌不尽 2020-12-13 19:50

There are several ways to do this, but I\'m not sure which one of them is the best.

Here\'s what I can think of:

  • Look for the process using pgrep.
3条回答
  •  猫巷女王i
    2020-12-13 20:23

    There are many ways to do it. PID files are the traditional way to do it. You could also hold a lock on a file, for example the program itself. This small piece of code will do the trick:

    use Fcntl ':flock';
    open my $self, '<', $0 or die "Couldn't open self: $!";
    flock $self, LOCK_EX | LOCK_NB or die "This script is already running";
    

    One advantage over PID files is that files automatically get unlocked when the program exits. It's much easier to implement in a reliable way.

提交回复
热议问题