How do you run multiple programs in parallel from a bash script?

前端 未结 15 1214
眼角桃花
眼角桃花 2020-11-22 06:31

I am trying to write a .sh file that runs many programs simultaneously

I tried this

prog1 
prog2

15条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:03

    Here is a function I use in order to run at max n process in parallel (n=4 in the example):

    max_children=4
    
    function parallel {
      local time1=$(date +"%H:%M:%S")
      local time2=""
    
      # for the sake of the example, I'm using $2 as a description, you may be interested in other description
      echo "starting $2 ($time1)..."
      "$@" && time2=$(date +"%H:%M:%S") && echo "finishing $2 ($time1 -- $time2)..." &
    
      local my_pid=$$
      local children=$(ps -eo ppid | grep -w $my_pid | wc -w)
      children=$((children-1))
      if [[ $children -ge $max_children ]]; then
        wait -n
      fi
    }
    
    parallel sleep 5
    parallel sleep 6
    parallel sleep 7
    parallel sleep 8
    parallel sleep 9
    wait
    

    If max_children is set to the number of cores, this function will try to avoid idle cores.

提交回复
热议问题