User1 User1 - 1 year ago 122
Linux Question

Bash: a sleep in a while loop gets its own pid

I have a bash script that does some parallel processing in a loop. I don't want the parallel process to spike the CPU, so I use a sleep command. Here's a simplified version.

(while true;do sleep 99999;done)&

So I execute the above line from a bash prompt and get something like:
[1] 12345

is the job number and
is the process ID (pid) of the while loop. I do a
kill 12345
and get:

[1]+ Terminated ( while true; do
sleep 99999;
done )

It looks like the entire script was terminated. However, I do a
ps aux|grep sleep
and find the sleep command is still going strong but with its own pid! I can kill the
and everything seems fine. However, if I were to kill the sleep first, the while loop starts a new
pid. This is such a surprise to me since the sleep is not parallel to the while loop. The loop itself is a single path of execution.

So I have two questions:

  1. Why did the sleep command get its own process ID?

  2. How do I easily kill the while loop and the sleep?

Answer Source
  1. Sleep gets its own PID because it is a process running and just waiting. Try which sleep to see where it is.
  2. You can use ps -uf to see the process tree on your system. From there you can determine what the PPID (parent PID) of the shell (the one running the loop) of the sleep is.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download