简体   繁体   English

Bash:在Shell脚本中使用进程ID

[英]Bash: Using process IDs in a shell script

I am a bit confused on the uses of PIDs and parent/children processes. 我对PID和父/子进程的使用感到有些困惑。 I have been reading up on them and I understand as far as the fact that when a program starts it makes an exact copy of itself (the child) and each of them have unique PIDs. 我一直在阅读它们,并且我了解一个事实,即程序启动时会对其自身(孩子)进行精确复制,并且每个人都有唯一的PID。 But I am not sure if I can use it in a shell to tell me when certain aspects of that shell program have finished. 但是我不确定是否可以在shell中使用它来告诉我该shell程序的某些方面何时完成。

For a better example (pseudo code): 举一个更好的例子(伪代码):

 for ((i = 0; i < 10; i++))
  for a_name in "${anArray[@]}";do
     a series of math equations that allow the values associated with a_name to run in the background simultaneously using '&' earlier in the code         
  done
wait

  for a_name in "${anArray[@]}";do
     same as above but diff equations
  done
wait
done

I am hoping to be able to see when any given value is finished in the command, so that that particular value can move on to the next for loop and command. 我希望能够看到命令中任何给定的值何时完成,以便该特定值可以移至下一个for循环和命令。

I have seen that wait can take a job identifier as an argument (wait%1 or wait $PPID) but I am not really sure how those would be implemented. 我已经看到,wait可以将作业标识符作为参数(wait%1或wait $ PPID),但是我不确定如何实现这些标识符。

Does anyone have advice on how to use PIDs and/or have a link to a super good tutorial? 有没有人对如何使用PID提出建议和/或提供超好教程的链接? (and I mean super good, I need some laymen's terms thrown in there) (我的意思是超级好,我需要在这里加上一些外行的条件)

Thanks! 谢谢!

You can wait on a single process: 您可以等待一个过程:

command ${array[0]} &
waiton=$!
# Do some more stuff which might finish before process $waiton
wait $waiton

You can wait on all children processes: 您可以等待所有子进程:

someLongRunningCommand &
(
    for value in "${array[@]}"; do
        command "$value" &
    done
    wait
)
# wait with no arguments waits on all children processes of the current
# process. That doesn't include `someLongRunningCommand`, as it is not
# a child of the process running the subshell.

Other situations are trickier and may be better handled by xargs , parallel , or some other method. 其他情况则比较棘手,可以通过xargsparallel或其他方法更好地处理。

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

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