简体   繁体   English

Shell:如何并行运行两个脚本A和B并在A结束时停止B

[英]Shell: how to run two scripts A and B in parallel and stop B when A is over

Suppose I have a shell script A.sh whose content is:假设我有一个 shell 脚本A.sh ,其内容是:

sleep 2
echo "A: 2s"
sleep 2
echo "A: 4s"
sleep 2
echo "A: 6s"

I also have a shell script B.sh whose content is:我还有一个 shell 脚本B.sh ,其内容是:

sleep 2
echo "B: 2s"
sleep 2
echo "B: 4s"
sleep 2
echo "B: 6s"
sleep 2
echo "B: 8s"
sleep 2
echo "B: 10s"

When I hope to run A and B in parallel, I created a script C.sh whose content is:当我希望并行运行A和B时,我创建了一个脚本C.sh ,其内容为:

sh A.sh &
sh B.sh &
wait

The output is: output 是:

B: 2s
A: 2s
A: 4s
B: 4s
A: 6s
B: 6s
B: 8s
B: 10s

In this way A and B can run in parallel.这样 A 和 B 可以并行运行。 Now I have one more requirement that is I hope to stop B when A is over.现在我还有一个要求,就是我希望在 A 结束时停止 B。 I followed the steps mentioned here and modified C.sh to:我按照此处提到的步骤并将C.sh修改为:

parallel -j2 --halt now,success=1 ::: 'sh A.sh' 'sh B.sh'

The output is: output 是:

A: 2s
A: 4s
A: 6s
parallel: This job succeeded:
sh A.sh

It seems B is not running in this way.看来B没有以这种方式运行。 Can anyone advise me what is the correct way to run two scripts A and B in parallel and stop B when A is over ?谁能告诉我并行运行两个脚本 A 和 B 并在 A 结束时停止 B 的正确方法是什么?

to run two scripts A and B in parallel and stop B when A is over?并行运行两个脚本 A 和 B 并在 A 结束时停止 B?

So do just that.所以就这样做吧。

sh B.sh &
b_pid=$!
{
    sh A.sh 
    kill "$b_pid"
} &
wait

I think it is running, but output is grouped by job by default, so you won't see the output from B till A is finished but when A finishes, the whole GNU Parallel process exits.我认为它正在运行,但是 output 默认按作业分组,所以你不会看到从 B 到 A 完成的 output 但是当 A 完成时,整个GNU Parallel进程退出。

Try switching to line-buffered output:尝试切换到行缓冲 output:

parallel --linebuffer sh ::: [AB].sh

If you're using a sufficiently modern bash (eg, this does not work in 3.2.5.7, but it does in 5.0.16, so it was introduced sometime between those), you can do:如果您使用的是足够现代的 bash(例如,这在 3.2.5.7 中不起作用,但在 5.0.16 中起作用,因此它是在两者之间的某个时间引入的),您可以执行以下操作:

a.sh &
b.sh &
wait -n
kill -- -$$

This waits until either process terminates and then sends a SIGTERM to all the jobs in the process group.这会等到任一进程终止,然后向进程组中的所有作业发送 SIGTERM。 Note, this will send the SIGTERM to all processes in the group, including the main script, so you may need to handle that.请注意,这会将 SIGTERM 发送到组中的所有进程,包括主脚本,因此您可能需要处理它。 If you want to restrict the jobs to which the signal is sent, run them in their own process group and send the signal appropriately.如果要限制信号发送到的作业,请在它们自己的进程组中运行它们并适当地发送信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM