Background Process Shell Scripting

I have a following program:

echofunc()
{
filename=$1
echo "reading $filename"
while read line
do
echo $line;
sleep 6;
done < $filename
}

split -5 new.dat
ls x* > input.dat
while read file
do
echofun $file &
done < input.dat

====================================================================================================================================
Here new.dat is a file which has many 300 line of records in it. So after split 60 files will be formed.

So in this program how do I limit only 10 instances of echofun() to run at a time ?

ls x* | head -10 >input.dat

The following script show a possible way (the SUBMIT_JOB_LIMIT is set the maximun instance count) :

#!/usr/bin/bash
#submit_jobs

the_job() {
   echo "$(date +%T) - Start of job $1"
   sleep $((RANDOM % 30))
   echo "$(date +%T) - End   of job $1"
}

SUBMIT_JOB_LIMIT=5
SUBMIT_JOB_SLEEP=5

submit_job() {
   job_act=$(jobs | wc -l)
   while ((job_act >= $SUBMIT_JOB_LIMIT))
   do
      sleep $SUBMIT_JOB_SLEEP
      job_act=$(jobs | wc -l)
   done
   (( job_cnt += 1 ))
   the_job $job_cnt &
}

for ((i=1; i<=10; i++))
do
   submit_job $i
done

An execution example :

$ submit_jobs
19:37:38 - Start of job 3
19:37:39 - Start of job 4
19:37:39 - Start of job 5
19:37:38 - Start of job 1
19:37:38 - Start of job 2
19:37:40 - End   of job 1
19:37:45 - Start of job 6
19:37:47 - End   of job 3
19:37:51 - Start of job 7
19:37:52 - End   of job 2
19:37:55 - End   of job 6
19:37:56 - Start of job 8
19:37:56 - Start of job 9
19:37:58 - End   of job 4
19:37:59 - End   of job 5
$ 19:38:02 - Start of job 10
19:38:06 - End   of job 9
19:38:14 - End   of job 8
19:38:20 - End   of job 7
19:38:29 - End   of job 10

Jean-Pierre.

Thanks Jean. I think it will work for me :slight_smile: