问题
I want to create a Bash script to launch parallel child processes. Is there a way to do this so that the child scripts still receive signals that are sent to the parent process?
Here's roughly how I want to launch child processes, but this doesn't meet my signaling criteria.
for (( i=0; i<9; i++ ))
{
{ echo $i start ; sleep 5s ; echo $i complete ; } &
}
wait
Because this works automatically in a C-program (that uses fork/exec
), I believe that it should be possible without the use of trap
-based signal forwarding -- which itself could be interrupted before the signals are forwarded.
One workaround for this is to use GNU-parallel
. I don't know what it's mechanism is, but it solves this problem -- as long as you are willing to restructure your loops into xargs
style syntax. GNU-parallel
does not solve the problem if the --semaphore
option is used.
I think the answer is here, but I don't know how to translate it to Bash: Signal sent to both child and parent process.
回答1:
It sounds as if you are fine with using GNU Parallel - just not the xargs style.
Will it be OK to use functions?
doit() {
# Trap 2 signals to show they are being given to the function
trap 'echo you hit Ctrl-C/Ctrl-\, now exiting..; exit' SIGINT SIGQUIT
echo $1 start
sleep 5s
echo $1 complete
}
export -f doit
seq 10 | parallel -u doit
or to avoid the pipe:
parallel -u doit ::: {1..10}
来源:https://stackoverflow.com/questions/16865123/how-to-launch-multiple-child-processes-that-will-automatically-receive-signals-s