How to Manage Child Process IDs in Bash Scripts?

0
10
Asked By SillySocks42 On

I'm working on a series of bash scripts that are meant to run in tandem, where the main script initiates several child scripts. For example, I might run `sudo childA.sh &` or `childB.sh &`, and some of these child scripts themselves spawn additional processes like `longprocess >> /dev/null & sleep 200 && kill $!`. My goal is to find a way to gather all the process IDs (PIDs) of these scripts and their spawned processes so that I can terminate them later, either after a specific time or if the main script is stopped. I have a simple cleanup function using `pgrep` to find child processes, but I'm having trouble getting it to reliably link to the correct child scripts started from the main script. Does anyone have a better method for tracking and managing processes spawned from a bash script?

5 Answers

Answered By TrickyTaco77 On

Another approach is to use `$!` to capture the PID of each spawned process as you go and store them in an array. Then, you can loop through this array to kill any processes when needed.

Answered By CuriousCat45 On

If you're open to exploring, there's a command called `coproc` in bash that creates a piped process and gives you a list of PIDs. However, you'd need to handle the I/O since it involves pipes.

Answered By WiseMarmot12 On

Consider adding an argument like `--id=12345` to your scripts and pass a different ID each time you run the main script. This way, when it comes time for cleanup, you can use `pgrep 'id=12345'` to identify the right processes. This method requires minimal changes to your scripts.

Answered By GadgetGuru99 On

One way to manage this is to have each child process write its PID to a common file or communicate through a named pipe. Then you can use `pkill` with the signal option to terminate those processes collectively. Additionally, it might help to name your child processes with a unique identifier to facilitate targeted kills.

Answered By CreativeCucumber88 On

You might want to track the PIDs right when you spawn them. This way, you'll have a clear list of processes to clean up later on. If you're looking to persist this list, consider writing it to a file. While it's a bit clunky, it can be effective. Just be aware that if the processes become orphaned, the method of checking parent processes might not work. The suggested approach of utilizing `ps` can help if you can identify the processes reliably.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.