0

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.

Community
  • 1
  • 1
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
  • I eventually developed [this approach](http://stackoverflow.com/a/17079664), but it relies on xargs (or GNU parallel) to manage the background processes. – Brent Bradburn Jul 07 '13 at 22:00

1 Answers1

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}
Ole Tange
  • 31,768
  • 5
  • 86
  • 104
  • Isn't this still using the xargs style? You have to replace the loop with a pipe -- just like with xargs. I appreciate the capabilities of GNU Parallel, but with this question I'm really trying to discover the built-in capabilities and workings of Bash. – Brent Bradburn Jul 07 '13 at 22:29
  • By the way: In [Mint 15](https://en.wikipedia.org/wiki/List_of_Linux_Mint_releases), parallel still requires the '--gnu' option (when installed via the standard package manager). – Brent Bradburn Jul 07 '13 at 22:29