Day 17: Checking process existence and listing processes (Proc::Find)

About the series: perlancar's 2014 Advent Calendar: Introduction to a selection of 24 modules which I published in 2014. Table of contents.

Proc::Find is little module that can help you write this shell idiom in Perl and avoid shelling out:

# check a process by name
ps ax | grep -q mplayer
if [[ $? == 0 ]]; then echo "mplayer process exists"; fi
pgrep mplayer
if [[ $? == 0 ]]; then echo "mplayer process exists"; fi

In Perl:

use Proc::Find qw(proc_exists);
say "mplayer process exists" if proc_exists(name=>'mplayer');

Proc::Find can find/list processes by other criteria other than name: pid, full commandline match, program's binary path, user/UID (other criteria can be added in the future). For example:

use Proc::Find qw(find_proc);
my $pids = find_proc(user => 'ujang'); # find all process owned by ujang

Note: this module is inspired after reading CPAN ratings for Proc::Exists. :-)

Leave a comment

About perlancar

user-pic #perl #indonesia