I have the necessity to run a script in background, now it is in etc/init.d
directory and run at the OS start up, that acting like follow:
For X seconds nothing happens then run a command, if any key is press on the keyboard it will run another command then restart the waiting time. Just to make a common example is like when the keyboard light goes off if nothing is pressed for a certain amount of time, then goes back on as soon as the keyboard has been pressed or the mouse moves.
This is my actual code:
#!/bin/bash
while true; do
sleep 1
read -rsn1 input
if [ "$input" = "ł" ]; then
echo "this is a key that you can't press"
else
echo "you press " "$input"
# command to run here if key has been pressed
fi
sleep 20
# command to run here after 20 secodns if key has not been pressed
done
trap control_c SIGINT
control_c()
{
stty sane
}
exit 0
When i tested the code on the terminal it works like ok. But if I run in background the program loops like a keyboard is pressed immediately after the sleep 20 line.
I running this script on Linux Mint Victoria 21.2 is based on Ubuntu 22.04
I didn't add the mouse yet because the keyboard's condition doesn't run as expected alredy.
edit:
As per @user1934428 suggestion i try to use evemu-recor
. This is the result,the test on the terminal was fine, but when run as background process doesn't get the keyboard feedback.
#!/bin/bash
start=$SECONDS
while true; do
sleep 1
input=$(sudo timeout 5s evemu-record /dev/input/event3 | grep "EV_KEY / KEY")
duration=$(( SECONDS - start ))
if [ "$input" = "" ]; then
if
(( $duration > 30 )); then
# command to run here
fi
else
# command to run here
input=""
duration=$(( SECONDS - duration ))
fi
done
trap control_c SIGINT
control_c()
{
stty sane
}