8acab83e241b49c61c6b5f0b84d1d5e72dac8007
[feisty_meow.git] / scripts / processes / process_manager.sh
1 #!/bin/bash
2
3 # process manager helper methods for bash.
4 #
5 # relies on the built-in process management to run a bunch of processes
6 # in the background, but will limit total number running to a maximum.
7 # demonstration method at the end of the file shows how to use the
8 # process managing methods.
9 #
10 # by chris koeritz
11
12 #hmmm: revisions desired someday:
13 #  + allow number of max processes to be passed in.
14 #  + 
15
16 # number of background processes.
17 bg_count=0
18
19 # maximum number of simultaneous background processes.
20 max_bg_procs=20
21
22 # number of processes to wait for if we hit the maximum.
23 procs_to_await=3
24
25 function start_background_action()
26 {
27   # launch the commands provided as parms in a subshell.
28   (for i in "${@}"; do eval "$i" ; done)&
29   #echo bg_count pre inc is $bg_count
30   ((bg_count++))
31   #echo bg_count post inc is $bg_count
32 }
33
34 function take_inventory()
35 {
36   start_background_action \
37       'echo "taking inventory..."' \
38       'bash $FEISTY_MEOW_SCRIPTS/core/inventory.sh'
39 }
40
41 function nechung()
42 {
43   start_background_action \
44       'echo "your nechung oracle pronouncement of the moment..."' \
45       '$BINDIR/nechung'
46 }
47
48 function login_on_xcg()
49 {
50   start_background_action \
51       'echo "summing directory output coming up..."' \
52       'perl $FEISTY_MEOW_SCRIPTS/files/summing_dir.pl'
53 }
54
55 # takes the number of processes to wait for, or just waits for one of them.
56 function wait_on_backgrounders()
57 {
58   local wait_count="$1"; shift
59
60   target_count=$(($bg_count - $wait_count))
61   if (($target_count < 1)); then target_count=1; fi
62   echo before waiting, count is $bg_count
63   while (($bg_count > $target_count - 1)); do
64     # wait for one job, let bash pick which.
65     wait -n
66     echo bg_count pre dec is $bg_count
67     ((bg_count--))
68     echo bg_count post dec is $bg_count
69   done
70   echo "done waiting, background process count is down to $bg_count."
71 }
72
73 # happily launches off different actions as background processes.
74 launcher_demonstrator()
75 {
76   while true; do
77     # pick a thing to do.
78     which=$(($RANDOM % 3))
79 #hmmm: not asynch yet!  make it so!
80     case $which in
81       0) take_inventory;;
82       1) nechung;;
83       2) login_on_xcg;;
84     esac
85
86     # we have reached the limit on processes and need to wait for a few, defined by
87     # procs_to_await variable at top.
88     if (($bg_count > $max_bg_procs - 1)); then
89       echo "have reached $max_bg_procs background processes threshold; waiting for $procs_to_await of them to complete."
90       wait_on_backgrounders $procs_to_await
91     fi
92
93   done
94 }
95
96 launcher_demonstrator;
97