How to Automatically Manage Multiple Background Processes in Bash?

0
1
Asked By CuriousCoder92 On

I'm trying to launch several background processes (like 4) in a Bash shell and keep them running while I interact with them asynchronously. I have a few requirements:

1. If a background process crashes, it should automatically restart unless it's restarting too rapidly, in which case it should stop trying to restart and print an error message.

2. I want functions created in my current shell session to send commands to these background processes individually or all at once. For example:
```
task1 () { echo "${@}" > task1's stdin; }
task2 () { echo "${@}" > task2's stdin; }
all () { echo "${@}" > task1's stdin; echo "${@}" > task2's stdin; }
```
If a process restarts, the function should redirect to the new instance's stdin, not a broken pipe.

3. Any output from these processes on stdout/stderr should be displayed with the process name appended (lowercase for stdout and uppercase for stderr), capturing complete lines of output.

Is it a good idea to do this all within a regular shell session, or should I create a separate script to manage this? I'm just trying to figure out how to keep all of these elements properly coordinated.

4 Answers

Answered By TechyTom123 On

You might want to check out coprocesses in Bash for handling your background tasks. They can be really handy! But do note that you can only have one active coproc at a time, so keep that in mind.

Answered By NerdyNina On

For managing stdin, Unix domain sockets are a great option since they’re persistent and maintain the connection even if a process restarts. As for the crashing processes, a simple `while true` loop in your script could handle the auto-restart seamlessly. You can also background those processes without issue.

FanOfNerdyNina -

Great idea! I hadn't thought of using sockets for this. I'll definitely try that out!

Answered By PipeMasterFlex On

Also, using `mkfifo` named pipes could really help your communication issue between the processes and the controller shell. You could set up a watchdog process to oversee and manage the lifecycle of your tasks without interruptions!

Answered By DevDude67 On

I've looked into this, and using a process manager like Foreman or its alternatives would suit your needs. It might help manage multiple background tasks better. For stdin, consider using named pipes; they've worked well for me in similar setups.

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.