pidofproc function in functions script

Dan Nicholson dbn.lists at gmail.com
Mon Jul 2 15:31:08 PDT 2007


On 7/2/07, dennisjperkins at comcast.net <dennisjperkins at comcast.net> wrote:
> >
> > while read line; do
> >   for pid in $line; do
> >     ...
> >   done
> > done < $pidfile
> >
>
>
> According to the LSB doc, only the first line of the pidfile should be read, so it looks like there could be more than one pid in the first line.  I don't know if there would ever be a second line or if it's just a precaution to ignore any other lines.

Cool, did not know this.

> Maybe this would work:
>
> read line < $pidfile
>
> while pid in $line; do
>    if  kill -0 $pid > /dev/null  ; then
>        pids="$pids $pid"
>    fi
> done

Yep. Except s/while/for/.

> I think "read" is builtin, so it should process faster than sed, altho it probably only adds milliseconds to execution time.  I thought of using "head", but if I remember correctly, it's not in /bin.

Using head or sed is fine, but the read builtin is more efficient. It
is a pet peeve of mine that processes are not forked when unnecessary.

> LSB also mentions /proc/$pid, /proc/$pid/cmdline, and /proc/$pid/exe.  I guess you could do this instead:
>
> read line < $pidfile
>
> while pid in $line; do
>    if  [ -d /proc/$pid ] ; then
>        pids="$pids $pid"
>    fi
> done

That would probably work fine. I don't know the history of using kill
-0, but kill(1) says that the exit code from sending signal 0 says
whether a process can receive signals or not. So, it's probably a bit
more robust than just seeing if the process is alive or not.

> LSB comments that /proc/$pid/exe should not be used by itself and that /proc/$pid/cmdline should be used with it.  I looked at them and they just contain the complete pathname of the script, but /proc/$pid/cmdline was always empty.  I think that this might be overkill, but until I find out what cmdline contains, I'm just guessing.

cmdline is the arguments passed to the process. Try this:

$ bash --login
$ cat /proc/$$/cmdline

/proc/*/exe would be interesting to look at, but would need some way
to read the symlink (and you'd have to be root). Another option would
be to use ps (ps -p $pid -o comm=). But that could be error prone
depending on how you called pidofproc (think /usr/sbin/smbd vs. smbd).

> I wonder if /proc/$pid looks different in multiprocessor systems?

It looks the same on mine.

--
Dan



More information about the lfs-support mailing list