Forking / Multi-Threaded Processes | Bash

前端 未结 8 1583
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 20:39

I would like to make a section of my code more efficient. I\'m thinking of making it fork off into multiple processes and have them execute 50/100 times at once, instead of

8条回答
  •  一生所求
    2020-11-30 21:03

    In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.

    Here is what works well for me:

    #!/bin/sh
    
    set -m # Enable Job Control
    
    for i in `seq 30`; do # start 30 jobs in parallel
      sleep 3 &
    done
    
    # Wait for all parallel jobs to finish
    while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done
    

    The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.

提交回复
热议问题