Home > Mobile >  Is there any way to monitor how many scripts are running at the same time using shell /script?
Is there any way to monitor how many scripts are running at the same time using shell /script?

Time:05-12

I have a .wav file generator every second that is ran from a shell script.

Here is a snippet of my script:

while true
do  
    ./Wav.exe & #My c   code
    sleep 1
done

The code itself take ~1.2s to run, (it records for 1 second and takes 0.2s to upload the .wav file and do other small tasks). Meaning if I want to create a .wav file every second, I will need to run two codes in parallel.

ie:

code 1 starts at time : 0.000s
recording 1 starts : 0.020s 
code 2 starts at time 1.000s
recording 2 starts at time 1.020s
recording 1 ends : 1.040s
code 1 ends at ~ 1.200s
code 3 starts at 2.000s
recording 3 starts at 2.020s
recording 2 ends at 2.060s
code 2 ends at ~ 2.220s
...etc

Meaning only 2 files are being run at a time because they take 1.2s to run and are needed to be every 1s. The problem being errors sometimes occur when 3 files are being run at a time for some reason ?? (the first file takes longer to close meaning a third file has time to open before it closes --> 3 files are open and a bug occurs).

Is there any way to add an if condition in the shell script that states:

if(2 files are already running)
{
Do not run another one
} 
Then go back to the top of the loop

CodePudding user response:

A command like this should work for getting the number of Wav.exe processes that are running:

ps ax | grep Wav.exe | wc -l

Then you can store the result in a variable and use Bash's test command (another name for [) to compare it to a threshold number like 2 or 3.

CodePudding user response:

Suggesting:

while true; do  
    ./Wav.exe & #My c   code
    sleep 1
    # if there are more than 2 "Wav.exe" processes
    if [[ $(pgrep -af "Wav.exe"|wc -l) -gt 2 ]]; then
      # wait for 1 extra sec
      sleep 1
    fi
done
  • Related