0

I am trying to use switch for executing a script(Let say script_a). For that i wrote a if condition in another script(Let say script_b). script_b is always running when rPi is on. While input of gpio is 1, script_a must be executed else script_b must be repeated. Here is my code:

script_b:

    if [ "$(gpio -g read 18)" = "1" ]
then
./script_a.sh&
else

sleep 0.1
./script_b.sh
fi

script_a:

if [ "$(gpio -g read 18)" = "0" ]
then

./script_b.sh&

else

sleep 0.1
./script_a.sh

fi

It works, however cpu usage is very high while gpio 18 is 0 in other words while script_b is repeating itself. How can i reduce cpu usage?

note that: i am not an expert with coding. Thank You

Edit:

So i decided to use if condition in while loop using only one script. I am trying to execute some processes while gpio 18 is 1 else do nothing. And i want to run that while loop infinitely. Here is my new code:

while [ "$(gpio -g read 18)" = "0" ]
do
sleep 0.1
done

while [ "$(gpio -g read 18)" = "1"  ]
do
#some processes are here
done

however it is exit while loop if i change switch 1 to 0.

Edit 2:

I added these lines at the and of the second while loop like that:

while [ "$(gpio -g read 18)" = "1"  ]
    do
    #some processes are here
if [ "$(gpio -g read 18)" = "0" ]
then
nohup ./stt.sh
exit 0
fi

done

And it is worked. But still cpu usage very high also there is only 20 mb free ram while this script is working. I am still open for suggestions. Are there anyway to reduce cpu and ram usage while doing my intended process.(By the way i am using htop for viewing cpu usage and free -h -s 1 for ram usage.)

2
  • script_b is repeating itself and it constantly reloads itself. Try a simple if..then..else inside a while loop, instead of reloading the script in every loop
    – foibs
    Commented Jan 20, 2014 at 13:03
  • i used while loop however it is ending when switch turn 0 from 1 Commented Jan 20, 2014 at 15:01

1 Answer 1

1

It's strongly implied you are using some kind of loop that's not shown, otherwise these would just run once and exit.

If so, this fork is an issue:

./script_b.sh&

& puts script_b into the background without waiting. You run script_a and it hits this point because gpio 18 is 0. So it forks an execution of script_b and then, with no delay at all, does the same thing over and over as long as gpio 18 is 0.

That is not far from being a fork bomb.

Again, presuming a loop, you probably want to ./script_b.sh & exit 0 so that one script actually stops when it launches the other one.

1
  • thank you for your answer but it is not changed the cpu usage. so i changed my approach, you can find edit in question. Commented Jan 20, 2014 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.