[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] grepps script...



1999-07-31-11:24:20 Stevie Strickland:
> This is a script I wrote to grep all the user's processes in the
> process table *without* returning any of the processes used to do
> it (unlike a simple `ps ax|grep foo`, which would randomly return
> the "grep foo" process)...

There's a standard idiom for doing that. Or rather, as standard as ps(1)
command-line args and output formats, which isn't very:-).

Under traditional ps(1) versions, where 'x' is an option you're likely to use,
add "c" and it'll omit the args, so that the grepper doesn't get snagged; for
the typical case where all you actually want is the pid this compresses to the
handy idiom

	pid=`ps axc|awk '$NF=="commandname"{print $1}'`

Under Solaris 2.x at least (I don't know about other System-V-ish pses) you
can achieve the same effect with

	pid=`ps -eo pid,comm|awk '$NF=="commandname"{print $1}'`

Frankly, I'd probably stop right about there most of the time; I confess I
don't use perl when shell seems to close to the job. But this isn't the Fun
With Bourne Shell list, so away we go....

There are lots of ways to tackle this in perl. Using one of the above idioms
would likely be the simplest, and those ps invocations are often faster
(particularly in the Solaris case) than other options that dump more info. But
for a given "ps x" format you could hit the nail with

	$pid = map{$_->[0]}grep{$_->[4] eq "commandname"}map{[split]}`ps ax`;

Or, to return to the command you have, perhaps:

	#!/usr/bin/perl -w
	die "No search string given!\n" if !defined($ARGV[0]);
	print map{$_->[0]}grep{$_->[5] eq $ARGV[0]}map{[$_, split]}`ps x`;

(tested for ps(1) output format from Red Hat Linux 6.0).

Still extremely nasty, though. Time to don the 7 League Boots and turn to
CPAN... looks like Proc::ProcessTable is a terrific match for the job, lessee,
it depends on Storable, ok that's one I'd been meaning to look at anyway,
right... Ok, I think

my($pid) = $_->{pid} for grep { $_->{fname} eq 'commandname' }
	@{Proc::ProcessTable->new('cache_ttys' => 1)->table};

would get the pid, formatting a report would be a little more work, there's a
nice example in the Proc::ProcessTable man page. If you cache_ttys it's
reasonably quick, if you don't it ain't:-).

-Bennett

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe