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?
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.
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With