在shell脚本中后台运行多个exec命令

问题描述 投票:0回答:1

我发现很难理解如何在这样的 shell 脚本中启动进程

mainscript.sh

exec command1 &
sleep 10
exec command2 &
sleep 10

我知道 exec 命令不会创建新进程,它只是将 bash 替换为要执行的命令,在这种情况下,当它以 & 运行时会发生什么

目前我看到这是 ps 输出,类似这样

UID      PID   PPID  C STIME TTY          TIME CMD
user+    1       0  0 16:43 ?        00:00:00 bash mainscript.sh
user+    48      1  9 16:43 ?        00:00:04 command1
user+    133     1  0 16:43 ?        00:00:00 command2
bash shell
1个回答
0
投票

当它以 & 运行时会发生什么

首先在

&
上创建一个子 shell。

user+    1       0  0 16:43 ?        00:00:00 bash mainscript.sh
user+    48      1  9 16:43 ?        00:00:04 bash mainscript.sh

然后该子 shell 被 command1

替换

user+    1       0  0 16:43 ?        00:00:00 bash mainscript.sh
user+    48      1  9 16:43 ?        00:00:04 command1

整条线,包括

exec
,它在子shell中运行。

© www.soinside.com 2019 - 2024. All rights reserved.