Rak*_*h.N 5 bash shell-script background-process
我在这里试图实现的是,通过脚本我同时运行 3 个不同的自定义应用程序,如果有任何应用程序退出,请通过通知或打印退出代码发出警报。
使用系统:Centos 6.8
(4.3 及更高版本)wait中的命令有一个选项:bash-n
如果
-n提供了该选项,则 wait 等待任何作业终止并返回其退出状态。
这意味着你可以这样做
command1 &
command2 &
command3 &
wait -n
printf 'One command exited with exit code %d\n' "$?"
Run Code Online (Sandbox Code Playgroud)
我考虑过 Bash 的wait -n,但它不会让你知道哪个子进程退出了。一个简单的 Perl 脚本怎么样?
#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";
sub spawn(@) {
my $pid = fork();
die "fork: $!" if not defined $pid;
if ($pid == 0) {
exec @_ or die "exec: $!";
}
return $pid;
}
# Commands to run
my $p1 = spawn '/bin/bash -c "sleep 6; kill $$"';
my $p2 = spawn '/bin/bash -c "sleep 4; exit 4"';
print "spawned PIDs $p1 and $p2\n";
while ((my $child = waitpid(-1, 0)) > 0) {
my $code = $? >> 8;
my $status = $? & 0xff;
printf "child %d finished with exit code %d (status/sig %d)\n", $child, $code, $status;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6134 次 |
| 最近记录: |