I want to run a series of commands concurrently such that if one of them dies they all stop.
Running multiple concurrent processes in a bash script, such that if one dies it takes the other ones down with it
113 Views Asked by Carl Patenaude Poulin At
2
There are 2 best solutions below
2
Carl Patenaude Poulin
On
This is my solution using job control.
- Whenever a job dies, it kills the parent script
- When the parent script dies, it kill the whole process group, including all jobs
I would hope that there's something simpler out there.
#!/usr/bin/env bash
# Mocks
function process () {
while true ; do
echo "Process $1 is working..."
sleep 10
done
}
# Actual implementation
trap terminate_entire_process_group EXIT
function terminate_entire_process_group () {
trap - EXIT
kill -15 -$$
}
function terminate_parent_process () {
trap - EXIT
kill $$ 2> /dev/null
}
(
trap terminate_parent_process EXIT
process 1
) &
(
trap terminate_parent_process EXIT
process 2
) &
wait
Related Questions in BASH
- When does Bash read heredocs?
- Why `set -o pipefail` gives different output even though the pipe is not failing
- Run an external command within jq to manipulate each values of a particular key
- API key 401 error in .env.development file
- How to "Enable mobile data" on a Huawei E3372 4G USB dongle using a bash script in Windows
- ImageMagick / Bash : pipe ignored(?) when filename format variable used
- MacOS Bash-Script: while read p and echo
- Parse command line arguments and write useful usage message without additional code
- JQ JSON - Values to Array
- why variable substitution is so different?
- postbank_pdf2csv: how to setup with Cygwin in Windows?
- Custom Bash functions & custom statements - Need some advice
- unexpected operator == in square brackets when trying to use gum lib
- How to disable a bash builtin inside a docker container
- Use sed or rename find series of alphabet then replace with with the same alphabet and a dash -
Related Questions in CONCURRENCY
- Unexpected inter-thread happens-before relationships from relaxed memory ordering
- Multiple Processes, Multiple Processors, Single Priority Queue - Java Thread-Safe and Concurrency -
- Efficiently processing many small elements of a collection concurrently in Java
- Zig Concurrency Vs Erlang Concurrency, is Zig less efficient than Erlang?
- Two Update statements on a row are running simultaneously with no locking in MYSQL
- How to Identify Specific Transaction Anomalies in a Given Schedule?
- How can I improve concurrent message processing with Google Task Queue?
- Why does the following program printf "thread 1 exists" twice in WSL2?
- ModelState.IsValid is false when its Data Model Concurrency Token is non nullable
- .NET A second operation was started on this context instance before a previous operation completed
- Can someone tell me what's wrong with mi Task.await?
- I am a beginner. More than problems, I have ideas I share my code ;D. NO RULES
- Understanding Potential Deadlock in Resource Pool Implementation Described in "Go in Action"
- Why are pre-allocated stacks expensive, given 64-bit virtual memory?
- Concurrency issues with server-sent events in Python
Related Questions in PROCESS
- How to get Java running parameters from Spring Boot running inside container in pod where no ps exist
- Module not found: Error: Can't resolve 'child_process' in 'react-cerbos-demo/node_modules/cerbos'
- Launch URL from C# and detect when browser is closed
- Communicating Java and Python processes freeze after a while when using readline() but not input()
- Can someone tell me what's wrong with mi Task.await?
- Initial Fastapi request is not being processed and stays on hold
- running the ld command through rust only works 50% of the time
- Dropping duplicated rows
- Which child will execute first when you call fork() and wait() multiple times?
- How to kill number of processes in cpanel
- How is Unix signal propagated to PGID in namespaces and what is the impact of NSpgid on process signal handling?
- Why does sudo kill -15 on sh and docker-compose PIDs not stop Docker containers?
- Can Process.Exited event get fired but the process hang in the system?
- Powershell script can not run when invoke in .NET process
- How to quickly terminate child processes in Go and proceed only when killed
Related Questions in JOBS
- is there a solution to run cron job command in cpanel only from my cPanel host?
- Getting "onNetworkChanged()" warning every few seconds in an Android application
- All of a sudden not working, using linked server to source getting "Communication link failure"
- PowerShell Toggle Button for Background Job Report Generation
- Retirgger aws glue job dynamically
- How generate multiple PDF's in Laravel?
- How to chain jobs in Dagster?
- Slurm - How to run a list of jobs n by n?
- How to bring a job to foreground and then disable job control in bash?
- Check duplicate jobs having same parameters in Laravel
- Can I know the background running process using "jobs" even i close the terminal in Linux?
- persisting a task + execute later and remove that task from queue using hangfire or quarts or builtin
- How to prevent Kubernetes scheduler from delaying job pods in pending state due to resource constraints
- Can excessive printing cause a job step to fail?
- Issue with Flink Job Failure when Using Custom Class as DataStreamSource Type
Related Questions in JOB-CONTROL
- SIGTSTP (Ctrl-Z) stops only the subshell, but the parent shell keeps running - interactive bash shell
- Shell script: spawn a terminal running a command, with the ability to suspend/resume job within the newely spawned terminal
- How to run shell builtin commands (that must change state of shell process) in background
- How are shell builtin commands run in background?
- VSCode integrated terminal will not allow job control for some reason
- Running multiple concurrent processes in a bash script, such that if one dies it takes the other ones down with it
- Why does sysvinit force the console to be its controlling terminal for any wait-type subprocess?
- how does the process know the SIGQUIT signal?
- Why does foreground job ignore job control signals when Bash is running as PID 1?
- How to track the copy activity using job control file or 0 kb files(fin) in ADF?
- Why is SIGTTOU signal being delivered to the process?
- Strange output on master side of a pty
- Bash wait terminates immediately?
- Docker Container won't stop with bash jobcontrol enabled
- combine ping with a background process
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
If you've got Bash 4.3 (2014) or later, this Shellcheck-clean code demonstrates one way to do it:
-noption forwaitwas introduced in Bash 4.3, so the code will not work with older versions of Bash.numvariable is[3]+.${num//[^[:digit:]]/}extracts the job number (3in this case) by removing all non-digit characters. See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for more information about${var//old/}.