2

I saw here the use of:

while ps | grep " $my_pid "

Question: In this kind of syntax while -command-, what is the while loop checking, return code of the command or stdout?

Elad Weiss
  • 3,662
  • 3
  • 22
  • 50

1 Answers1

1

It's checking the return value of the process pipeline, which happens to be the return value of the last element in that pipeline (unless pipefail is set, but it usually isn't). The bash doco has this to say:

while list-1; do list-2; done

The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero.

Elsewhere, it states:

The return status of a pipeline is the exit status of the last command

So this while statement continues as long as grep returns zero. And the grep doco states:

The exit status is 0 if a line is selected.

So the intent is almost certainly to keep looping as long as the process you're monitoring is still alive.


Of course, this is a rather "flaky" way of detecting if your process is still running. For a start, if my_pid is equal to 60, that grep is going to return zero if any of the processes 60, 602, or 3060, are running.

It's also going to return zero if, like I often have, you have some number of sleep 60 or sleep 3600 processes in flight, no matter their process ID.

Perhaps a better way, assuming you're on a system with procfs, is to use something like:

while [[ -d /proc/$my_pid ]] ; do ...

This will solve everything but the possibility that process IDs may be recycled so that a different process may start up with the same PID between checks but, since most UNIX-like systems allocate PIDs sequentially with wrap-around, that's very unlikely.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953