Shell--wait and multi-process concurrency

Source: Internet
Author: User

Open multiple sub-processes in the script with & background, and use the wait command to make these sub-processes execute in parallel.

Example 1:

fun1 () {whiletruedoesecho1sleep1done  }fun2 () {whiletruedoecho2sleep 1  Done  &&Wait

Example 2:

#!/bin/Bash for((i=0;i<5; i++)) DoSleep 3;Echoa Done#运行需要15秒. #!/bin/Bash for((i=0;i<5; i++)) Do{Sleep 3;EchoA}& Donewait#打开5个子进程并行, it only takes 3 seconds to run. 

Example 3:

Use pipeline FIFO file to handle concurrency, this example goes from https://my.oschina.net/sanpeterguo/blog/133304

This example allows bloggers to learn a lot, using the pipeline, read-u,exec related knowledge, follow-up blog updated gradually.

#!/bin/bash#author: [Email protected]#Date:2013.05. -#sub Process Dosomethingfunctiona_sub_process {Echo "processing in PID [$$]"    Sleep 1} #创建一个fifo文件FIFO_FILE=/tmp/$.fifoMkfifo$FIFO _file# associated FIFO files and fd6exec6<>$FIFO _file # fd6 point to FIFO typeRM$FIFO _file# Maximum number of processes Process_num=4#向fd6中输入 $PROCESS _num a carriage return . for((idx=0;idx< $PROCESS _num;idx++)); Do    Echo Done>&6#处理业务, you can use the while for((idx=0;idx< -; idx++)); DoRead-u6 #read-The U6 command executes once, which is equivalent to trying to get a row from fd6, and if it is not, blocks the #获取到了一行后, fd6 a line, starts processing the child process, and the child process executes in the background {a_sub_process&& {          Echo "Sub_process is finished"      } || {         Echo "Sub Error"#完成后再补充一个回车到fd6中, release a lockEcho>&6# when the process is finished, add a carriage return to the FD6, that is, fill in the read-U6 minus the one}& Done#关闭fd6exec6>&-

Shell--wait and multi-process concurrency

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.