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

Re: OT Shell tricks: I'll kill you later

Karsten M. Self wrote:
>     while sleep 600
>     do
>         ps aux | awk '/[w]hois/ {print $2}' | ( sleep 30; xargs kill )
>     done

Clever.  I like the concept.  But I don't like the ps side of the
implementation.  The format is slightly different depending upon the
state of the process.  Also the search can match too much and kill
similarly named processes.

Personally I am more familiar with the SysV format rather than the BSD
format.  'ps aux' is roughly equivalent to 'ps -ef'.  But you don't
generally want the full output output for what you are doing.  Is
there an equivalent to SysV 'ps -e' in the BSD format?  In any case
that is a better format for looking for processes by name.  Then we
can make the awk test a little more precise.

  ps -e | awk '$NF == "whois" {print $1}' | ( sleep 30; xargs kill )

That avoids the collateral damage from similarly named processes.  It
avoids needing the [w]hois workaround nicely.  But a process which is
named exactly the same can still be killed.  I assume you are running
this process as root and killing user processes would be undesireable.
Of course if it is run as a unique non-root user then the system
permissions will prevent it from actually killing other proceses.  But
we can avoid it even trying.  Let's select only our own processes with
'ps -u userid'

  ps -u root | awk '$NF == "whois" {print $1}' | ( sleep 30; xargs kill )

That avoids killing other user's processes.  It uses only standard
utilities which is rather nice.  But there is a procps utility which
can shorten things up a little.

  pgrep -xu root whois | ( sleep 30; xargs kill )

Personally I would probably leave the ps | awk in any script that I
would write.  It uses only standard utilities and would work on other
systems without change.  But on the commandline knowing it was
available I would probably use the pgrep since it is simpler to type.


P.S. I really enjoyed your title.

Attachment: pgpyl71aJhXU1.pgp
Description: PGP signature

Reply to: