in reply to file used by process

I have a somewhat similar situation, and here is how I solved it. My problem was on Linux, but hopefully there is something to be gained from this solution.

I only included a snippet from my entire script (which does a few other things). I have not run this snippet by itself, but I did run it with perl -c to make sure the syntax was OK at least. I also had to sanitize a few values before posting it publicly, so I hope that I didn't make an error doing that either.

#!/usr/bin/perl -w use strict; use warnings; use Data::Dumper; # Mnemonic: "lh" = log file handle. open my $lh, '>', '/tmp/this_script.log' or die "Opening debug log fai +led: $!"; ###################################################################### +######## # # Kill any process still holding a file open in /usr/local/tomcat. # ###################################################################### +######## my @pids = lsof_grep('/usr/local/tomcat'); print $lh scalar localtime; print $lh "\n+++++ Contents of \@pids (lsof_grep) +++++\n"; print $lh Dumper(\@pids); for my $pid (@pids) { # This is the first time a few of these processes are being told t +o shut # down. Thus, we need to send a signal that lets them close their + open # files, which is the entire point of this whole script. kill 'TERM', $pid; } # Give those processes up 1 second per process to quit. sleep @pids; # Run lsof again. We'll send a stronger signal this time to any proce +sses # that still have Tomcat files open. @pids = lsof_grep('/usr/local/tomcat'); print $lh scalar localtime; print $lh "\n+++++ Contents of \@pids (lsof_grep, 2nd time) +++++\n"; print $lh Dumper(\@pids); for my $pid (@pids) { kill 'KILL', $pid; } close $lh; exit 0; sub lsof_grep { my $re = shift; my @lsof_out = qx{/usr/sbin/lsof}; my %openfiles; for my $line (@lsof_out) { if ($line =~ m{$re}) { my @fields = split /\s+/, $line; $openfiles{$fields[-1]} = $fields[1]; } } # %openfiles will have the same PID multiple times. Once for each + open # file it has. However, we don't want the PID repeated in the ret +urn # list. We still need to print the contents of %openfiles for pot +ential # debug purposes, however. print $lh scalar localtime; print $lh "\n+++++ Contents of \%openfile +++++\n"; print $lh Dumper(\%openfiles); # %seen is only used in the next grep to make the expression work, + because # hash keys are unique. my %seen; return grep { !$seen{$_}++ } values %openfiles; }