因此,我有一个小的 systemd 脚本,该脚本应该在我的笔记本电脑处于挂起模式 x 秒后使其进入休眠状态(文件名为/lib/systemd/system-sleep/0000rtchibernate.sh
):
#!/bin/bash
# Script name: /usr/lib/systemd/system-sleep/0000rtchibernate.sh
# Purpose: Auto hibernates after a period of sleep
# Edit the "autohibernate" variable below to set the number of seconds to sleep.
curtime=$(date +%s)
autohibernate=10 #for testing purposes
sleeptime=2
logging=true
logfile="/lib/systemd/system-sleep/0000rtchibernate.log"
skipfile="/lib/systemd/system-sleep/0000rtchibernate.skip"
lockfile="/tmp/rtchibernate.lock"
echo "$curtime $1" >>/tmp/autohibernate.log
if [ "$2" = "hibernate" ]; then
if [ "$logging" = true ]; then
echo "$(date) : Hibernating, doing nothing" >> $logfile
fi
exit 0
fi
if [ "$1" = "pre" ]; then
# only set timer if file 0000rtchibernate.skip doesn't exist
if [ ! -f $skipfile ]; then
# Suspending. Record current time, and set a wake up timer.
if [ "$logging" = true ]; then
echo "$(date) : Suspending" >> $logfile
fi
echo "$curtime" > $lockfile
rtcwake -m no -s $autohibernate
fi
fi
if [ "$1" = "post" ]; then
if [ -f $skipfile ]; then
# if skipfile is present on resume, remove it
if [ "$logging" = true ]; then
echo "$(date) : Removing skipfile" >> $logfile
fi
rm $skipfile
else
# Coming out of sleep
sustime=$(cat $lockfile)
rm $lockfile
# Did we wake up due to the rtc timer above?
if [ $(($curtime - $sustime)) -ge $((autohibernate-5)) ]; then
if [ "$logging" = true ]; then
echo "$(date) : Hibernating" >> $logfile
fi
# Then hibernate
/bin/systemctl hibernate
return_val=$?
if [ "$logging" = true ]; then
echo "$(date) : Return value of systemctl hibernate was $return_val" >> $logfile
fi
# if hibernation fails, create skipfile and suspend
if [ "$return_val" -gt 0 ]; then
if [ "$logging" = true ]; then
echo "$(date) : Hibernation failed. Creating skipfile and suspending" >> $logfile
fi
touch $skipfile
/bin/systemctl suspend
fi
else
if [ "$logging" = true ]; then
echo "$(date) : Waking up early, not hibernating" >> $logfile
fi
# Otherwise cancel the rtc timer and wake up normally.
rtcwake -m no -s 1
fi
fi
fi
(代码最初来自这里,我只适配了systemd)
挂起笔记本电脑时脚本运行良好,以下是日志输出:
Di 20. Mär 10:53:31 CET 2018 : Suspending
Di 20. Mär 10:53:44 CET 2018 : Hibernating
Di 20. Mär 10:53:44 CET 2018 : Return value of systemctl hibernate was 1
Di 20. Mär 10:53:44 CET 2018 : Hibernation failed. Creating skipfile and suspending
我的问题是/bin/systemctl hibernate
和/bin/systemctl suspend
的返回值都是 1,并没有按照预期执行,尽管从终端窗口运行时一切都正常。顺便说一句,我在 Ubuntu 18.04 上。任何帮助都感激不尽 :-)