Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for background processes to finish before exiting script

How do I make sure that all my background processes have finished execution before I exit my script (TCL/Bash).

I was thinking of writing all my background process pids to a pidfile. And then at the end pgrep the pidfile to see if any processes are still running before I exit.

Is there some simpler way to do this? And is there a TCL specific way to do this?

like image 294
egorulz Avatar asked Jan 10 '13 09:01

egorulz


People also ask

Does a shell script wait for command to finish?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

How do you stop background processes in Bash?

Use CTRL + Z To put the said process in the background, we can press the CTRL + Z key and suspend the job. It is good to note that this does not terminate the process; it only freezes it.

How do I run a script in the background process?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.


2 Answers

If you want to wait for jobs to finish, use wait. This will make the shell wait until all background jobs complete. However, if any of your jobs daemonize themselves, they are no longer children of the shell and wait will have no effect (as far as the shell is concerned, the child is already done. Indeed, when a process daemonizes itself, it does so by terminating and spawning a new process that inherits its role).

#!/bin/sh { sleep 5; echo waking up after 5 seconds; } & { sleep 1; echo waking up after 1 second; } & wait echo all jobs are done! 
like image 178
William Pursell Avatar answered Sep 22 '22 16:09

William Pursell


You can use kill -0 for checking whether a particular pid is running or not.

Assuming, you have list of pid numbers in a file called pid in pwd

while true; do      if [ -s pid ] ; then         for pid in `cat pid`         do               echo "Checking the $pid"             kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid         done     else         echo "All your process completed" ## Do what you want here... here all your pids are in finished stated         break     fi done 
like image 33
Suku Avatar answered Sep 21 '22 16:09

Suku