Shell脚本等待后台命令

Shell脚本等待后台命令

我正在写一个脚本,但是我需要一些东西,但找不到方法......

我需要在后台“command1 &”中创建一个命令,然后在脚本中的某个位置我需要等待它完成,然后再执行 command2。基本上,我需要这个:

注意:每个命令都在特定目录中运行!在 while 循环结束时,我的 command1 创建了 4 个目录,其中每个目录都运行特定进程,因此运行的进程总数为 4

a=1

while [$a -lt 4 ]

     . command1
   #Generates 1 Process  

     a= `export $a +1`
done

   #Wait until the 4 process end and then run the command2 

    . command2

我见过一些关于wait带有 pid 进程号的命令,但这也不起作用。

答案1

您可以使用该命令wait PID等待进程结束。

您还可以使用以下命令检索最后一个命令的 PID$!

在你的情况下,这样的事情会起作用:

command1 & #run command1 in background
PID=$! #catch the last PID, here from command1
command2 #run command2 while command1 is running in background
wait $PID #wait for command1, in background, to end
command3 #execute once command1 ended

编辑完成后,由于您有多个 PID 并且您了解它们,因此您可以执行以下操作:

command1 & #run command1 in background
PID1=xxxxx
PID2=yyyyy
PID3=xxyyy
PID4=yyxxx
command2 #run command2 while command1 is running in background
wait $PID1 $PID2 $PID3 $PID4 #wait for the four processes of command1, in background, to end
command3 #execute once command1 ended

答案2

最干净的方法是让您comamnd1返回已启动进程的 PID,并wait按照 @LaurentC 的建议在每个进程上使用回答

另一种方法是这样的:

## Create a log file
logfile=$(mktemp)

## Run your command and have it print into the log file
## when it's finsihed.
command1 && echo 1 > $logfile &

## Wait for it. The [ ! -s $logfile ] is true while the file is 
## empty. The -s means "check that the file is NOT empty" so ! -s
## means the opposite, check that the file IS empty. So, since
## the command above will print into the file as soon as it's finished
## this loop will run as long as  the previous command si runnning.
while [ ! -s $logfile ]; do sleep 1; done

## continue
command2

答案3

如果使用以下方法,则在 while 循环之后可能不需要特殊的“等待所有进程”。该循环将等待当前command1完成,然后再循环回到顶部。请谨慎对待任何建议。请注意,我所做的唯一一件事就是添加& wait $!到您的command1.

a=1
while [$a -lt 4 ]
     . command1  & wait $!
   #Generates 1 Process  
     a= `export $a +1`
done

相关内容