How to launch multiple child processes that will automatically receive signals sent to parent

梦想的初衷 提交于 2019-12-13 21:24:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!