障碍在bash,可以将它轻松完成? [英] Barrier in bash, can it be done easily?

查看:90
本文介绍了障碍在bash,可以将它轻松完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个并行执行三个脚本bash脚本

Let's say I have a bash script that executes three scripts in parallel

./script1 &
./script2 &
./script3 &

现在,让我们说./script4取决于SCRIPT1,SCRIPT2和script3。我怎样才能迫使它等待的,同时还并行执行的三个脚本?

Now, let us say that ./script4 depends on script1, script2 and script3. How can I force it to wait for those, while still executing the three scripts in parallel?

推荐答案

您可以使用 内置的的,并在其他一些炮弹。结果
(见等效的命令 WAITFOR 在Windows上)

You can use wait a built-in command available in Bash and in some other shells.
(see equivalent command WAITFOR on Windows)

等待每个指定的进程完成并返回其终止
  状态。

Wait for each specified process to complete and return its termination status.

Syntax
      wait [n ...]
Key
   n   A process ID or a job specification

每个 N 可以是一个进程ID或工作规范;如果作业
  说明书中给出,在作业的管道中的所有进程都
  等了。

Each n can be a process ID or a job specification; if a job specification is given, all processes in that job's pipeline are waited for.

如果 N 没有给出,所有当前活动的子进程等待
  为,并且返回状态是零。

If n is not given, all currently active child processes are waited for, and the return status is zero.

如果 N 指定了一个不存在的进程或作业,返回状态是
   127 。否则,返回状态是最后一道工序或作业的退出状态等待。

If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for.

无限期地等待所有当前活动的子进程将全部结束(即,在这种情况下,三个脚本)。

Simple solution

Below wait waits indefinitely for all currently active child processes to be all ended (i.e. in this case the three scripts).

./script1 &
./script2 &
./script3 &
wait       # waits for all child processes
./script4

店铺的PID壳局部变量

./script1 & pid1=$!
./script2 & pid2=$!
./script3 & pid3=$!
wait $pid1 $pid2 $pid3  # waits for 3 PIDs
./script4

在存放临时文件的PID

./script1 & echo $! >1.pid
./script2 & echo $! >2.pid
./script3 & echo $! >3.pid
wait $(<1.pid) $(<2.pid) $(<3.pid)
rm 1.pid 2.pid 3.pid            # clean up
./script4

这最后的解决方案,污染了当前目录中的三个文件( 1.pid 2.pid 3.pid )。其中一个文件可能会调用之前被破坏。此外,这些文件可能被留在文件系统崩溃的情况下。

This last solution pollutes the current directory with three files (1.pid, 2.pid and 3.pid). One of these file may be corrupted before wait call. Moreover these files could be left in the file-system in case of crash.

这篇关于障碍在bash,可以将它轻松完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆