reyjrar has asked for the wisdom of the Perl Monks concerning the following question:

I'm avoiding system calls in this perl program I'm writing and I need to check to see if some pid is currently active.. I'd prefer to do this without modules (cuz it seems simple) so here's what I came up with:
#!/usr/bin/perl use strict; my $pid = $ARGV[0] or die "usage: $0 pid\n"; my $group = getpgrp $pid; print "$pid\'s group is $group\n"; if($group >= 0) { print "$pid is active\n"; } else { print "$pid doesn't exist\n"; }
Because what I noticed during some testing is that getpgrp returns -1 if the pid doesn't exist, a number > 0 if pid exists, and 0 if the pid is 1 (init). Anyone else played with this and have any advice/warnings about doing it this way?

Replies are listed 'Best First'.
Re: Checking PIDs without system calls
by AgentM (Curate) on Mar 06, 2001 at 02:13 UTC
    Using kill, you can pass signal 0 which is essentially a pid ping. This is apparently the most portable thing I've come across for this. And, o yeah, don't forget that I actually meant sigqueue instead of kill. :-D (POSIX dude, ovrnout)
    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
      you da man.. guess I should brush up on signals :)
      thanks much..
      -brad..
Re: Checking PIDs without system calls
by tadman (Prior) on Mar 06, 2001 at 04:00 UTC
    A cheap hack, but will depend on how your OS operates:      if (-d "/proc/$pid") { ... } This will likely work with most UNIX variants. As a bonus, you can examine the command line parameters of that process to see if it's the one you were expecting. On Linux, at least, this is available in a pseudo-file:
    sub GetProcessCommand { my ($pid) = @_; return (open (PID, "/proc/$pid/cmdline") && <PID>); }
    This way you can validate the "authenticity" of the process1:
    # Check for buddy named 'xyz-proc' if (GetProcessCommand($pid) =~ /xyz\-proc/) { ... }
    Sometimes you will find a process active in that slot, but for some reason it isn't yours.
    1. This "authentication" is pretty loose, so be sure to check the owner of the process too. You can masquerade your process as anything you like by setting $0, after all, but you can't change the uid of the process so easily.