27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

Example 28−1. Finding the process associated with a PID<br />

#!/bin/bash<br />

# pid−identifier.sh: Gives complete path name to process associated with pid.<br />

ARGNO=1 # Number of arguments the script expects.<br />

E_WRONGARGS=65<br />

E_BADPID=66<br />

E_NOSUCHPROCESS=67<br />

E_NOPERMISSION=68<br />

PROCFILE=exe<br />

if [ $# −ne $ARGNO ]<br />

then<br />

echo "Usage: `basename $0` PID−number" >&2 # Error message >stderr.<br />

exit $E_WRONGARGS<br />

fi<br />

pidno=$( ps ax | grep $1 | awk '{ print $1 }' | grep $1 )<br />

# Checks for pid in "ps" listing, field #1.<br />

# Then makes sure it is the actual process, not the process invoked by this script.<br />

# The last "grep $1" filters out this possibility.<br />

if [ −z "$pidno" ] # If, after all the filtering, the result is a zero−length string,<br />

then<br />

# no running process corresponds to the pid given.<br />

echo "No such process running."<br />

exit $E_NOSUCHPROCESS<br />

fi<br />

# Alternatively:<br />

# if ! ps $1 > /dev/null 2>&1<br />

# then # no running process corresponds to the pid given.<br />

# echo "No such process running."<br />

# exit $E_NOSUCHPROCESS<br />

# fi<br />

# To simplify the entire process, use "pidof".<br />

if [ ! −r "/proc/$1/$PROCFILE" ] # Check for read permission.<br />

then<br />

echo "Process $1 running, but..."<br />

echo "Can't get read permission on /proc/$1/$PROCFILE."<br />

exit $E_NOPERMISSION # Ordinary user can't access some files in /proc.<br />

fi<br />

# The last two tests may be replaced by:<br />

# if ! kill −0 $1 > /dev/null 2>&1 # '0' is not a signal, but<br />

# this will test whether it is possible<br />

# to send a signal to the process.<br />

# then echo "PID doesn't exist or you're not its owner" >&2<br />

# exit $E_BADPID<br />

# fi<br />

exe_file=$( ls −l /proc/$1 | grep "exe" | awk '{ print $11 }' )<br />

# Or exe_file=$( ls −l /proc/$1/exe | awk '{print $11}' )<br />

#<br />

# /proc/pid−number/exe is a symbolic link<br />

# to the complete path name of the invoking process.<br />

if [ −e "$exe_file" ] # If /proc/pid−number/exe exists...<br />

Chapter 28. /dev and /proc 313

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!