![Cron 未运行键盘背光控制脚本](https://linux22.com/image/1139214/Cron%20%E6%9C%AA%E8%BF%90%E8%A1%8C%E9%94%AE%E7%9B%98%E8%83%8C%E5%85%89%E6%8E%A7%E5%88%B6%E8%84%9A%E6%9C%AC.png)
我正在尝试编写一个脚本,在 30 秒不活动后关闭键盘背光以节省电量。它需要 root 权限才能正常运行。在当前尝试中,我将其实现为 Cron 作业。脚本如下:
#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# requires installation of xprintidle
# if user idle for greater than or equal to 30s and
# keyboard backlight is on, turn backlight off
echo 'Start script' >> /home/lair001/cronout.txt
CheckIdle() {
if [ 30000 -le $(xprintidle) ] && [ $(cat /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness) -ne 0 ]
then
echo '0' > /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness
echo 'Attempted to turn off backlight' >> /home/lair001/cronout.txt
fi
}
# since cron jobs can only be scheduled up to
# once a minute, run CheckIdle twice with a 31s
# delay between iterations
CheckIdle
echo 'Ran first check' >> /home/lair001/cronout.txt
sleep 31s
CheckIdle
echo 'Ran second check' >> /home/lair001/cronout.txt
root 的 cron 文件如下:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
* * * * * /usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1
从 cron 日志来看,该命令似乎正在运行:
Aug 4 23:25:01 Robotron CRON[5310]: (root) CMD (/usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1)
Aug 4 23:26:01 Robotron CRON[5396]: (root) CMD (/usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1)
Aug 4 23:27:01 Robotron CRON[5399]: (root) CMD (/usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1)
Aug 4 23:28:01 Robotron CRON[5452]: (root) CMD (/usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1)
Aug 4 23:29:01 Robotron CRON[5459]: (root) CMD (/usr/bin/thinpad_kb_bl_dr_idl.sh & >/dev/null 2>&1)
但是,cronout.txt 仍然是空的。该脚本以 sudo 或 root 身份从终端正常运行。最初,我尝试将此脚本实现为持久的后台进程,但它一直停止:
# !/bin/sh
# requires installation of xprintidle
while true
do
# if user idle for greater than or equal to 30s and
# keyboard backlight is on, turn backlight off
if [ 30000 -le $(xprintidle) ] && [ $(cat /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness) -ne 0 ]
then
echo '0' > /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness
# else if user pressed a key within the past 30s and
# keyboard backlight is off, put backlight on dim
elif [ 30000 -gt $(xprintidle) ] && [ $(cat /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness) -eq 0 ]
then
echo '1' > /sys/devices/platform/thinkpad_acpi/leds/tpacpi::kbd_backlight/brightness
fi
# Check every 2 seconds
# Faster check cycles means that the backlight turns on
# quicker after keystroke at the expense of
# greater CPU and power consumption
sleep 2s
done
在找到解决权限问题和无限循环的方法后,仍然想实现一种通过用户活动打开键盘背光的方法。