sub single_instance{ $SIG{INT} = sub {exit()}; my ($prog) = $0 =~ m|(?:.*[/\\])?(.*)$|; my $tmp_dir = $^O =~ "MSWin32" ? "C:/Windows/Temp" : "/tmp"; my $lockfile = "$tmp_dir/$prog.pid"; local *PID_FILE; open(SLOCK,">$tmp_dir/$prog.slock") or die("single_instance(): Can't open slock: $!\n"); flock(SLOCK,2); if (-e $lockfile){ open(PID_FILE, "<$lockfile") or die("single_instance(): Can't open $lockfile: $!\n"); my $running_pid = ; close(PID_FILE); chomp($running_pid); if (kill 0, $running_pid){ die("Already running as pid $running_pid\n"); } } open(PID_FILE, "+>$lockfile") or die("single_instance(): Can't open $lockfile: $!\n"); print PID_FILE "$$\n"; close(PID_FILE); close(SLOCK); chmod(0666, $lockfile); eval "END {unlink '$lockfile'}"; die("single_instance(): $@\n") if($@); }