Sleep in a while loop gets its own pid

User1 picture User1 · Dec 15, 2010 · Viewed 10.8k times · Source

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

Where [1] is the job number and 12345 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 sleep and everything seems fine. However, if I were to kill the sleep first, the while loop starts a new sleep 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

Marcus Borkenhagen picture Marcus Borkenhagen · Dec 15, 2010
  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.