gpt4 book ai didi

linux - Bash 脚本无限循环关闭

转载 作者:太空宇宙 更新时间:2023-11-04 12:58:55 26 4
gpt4 key购买 nike

我写了一个简短的 bash 脚本,它每 10 秒收集一次 CPU 温度,并将其与其他一些数据一起输出到一个文件中。在终端中运行脚本工作得很好。但是,一旦我将脚本设置为在启动时运行,我遇到了 2 个问题:

- 使用 gedit 打开生成的 .txt 文件会导致:“gedit 无法检测到字符编码。请检查您是否在尝试打开二进制文件。”从菜单中选择一种字符编码,然后重试。”使用 Libre Writer 打开文件工作正常,文件具有正确的数据。

-当我在将脚本放入/etc/init.d/并运行 update-rc.d 后第一次尝试关机时,PC 花了莫名其妙的时间来完成它,以至于我不得不手动关机。

这是脚本代码:

#!/bin/bash

readonly DIR_PATH='/home/ivan/Documents/temp_data/' # path to output dir, change to yours, don't use HOME variable

while true; do
temps_str=$(sensors | grep "Physical" | tr -dc "[:digit:][^ °.C]") # extract numbers from sensors command output
temps_str=${temps_str:5} # remove first 5 characters, they are ' ', ' ', '0', ' ', ' ' and useless
temps_array=($temps_str) # convert string to array

temp_now=${temps_array[0]} # CPU temp now
temp_high=${temps_array[1]} # highest CPU temp recorded in this session
temp_max=${temps_array[2]} # CPU temp at which PC turns off

dt=$(date +%d-%m-%Y) # date, format: dd-mm-yyyy
time=$(date +%H:%M:%S) # time, format: HH:MM:SS

# create output directory if it doesn't already exist
if [ ! -d $DIR_PATH ]; then
mkdir -m 755 $DIR_PATH
fi

echo $time $temp_now $temp_high $temp_max >> ${DIR_PATH}${dt}.txt # write to output file

sleep 10 # wait 10 seconds
done

这是输出文件的格式:

17:22:21 58.0°C 87.0°C 105.0°C

17:22:31 56.0°C 87.0°C 105.0°C

17:22:41 58.0°C 87.0°C 105.0°C

17:22:51 59.0°C 87.0°C 105.0°C

17:23:01 58.0°C 87.0°C 105.0°C

17:23:11 59.0°C 87.0°C 105.0°C

17:23:21 60.0°C 87.0°C 105.0°C

17:23:32 63.0°C 87.0°C 105.0°C

17:23:42 63.0°C 87.0°C 105.0°C

当我收到“永久关机”时,我手动将其关闭。重新启动后,文件显示脚本仍在运行并写入文件,而 PC 已卡住,然后是一行 #s(可能是在手动关机期间写入的)。我想知道是什么原因导致卡住以及为什么 .txt 文件字符集会“损坏”?

最佳答案

/etc/init.d 中的脚本用于启动和停止服务。因此,他们需要准备好接受命令行参数 startstop。 (如果他们也接受诸如 restartstatus 之类的参数,那就太好了。)

当您将这些脚本之一的符号链接(symbolic link)放在 /etc/rcN.d 中的目录中时,将使用参数 start停止:

  • 在启动时,参数取决于符号链接(symbolic link)的名称是否以 S(start)或 K 开头(stop -- 这个字母代表“kill”)。

  • 关闭时,参数将为stop

(以上是 debian 行为,取自 Debian policy manual 。)

您的脚本不是这种形式。它只是运行监控程序。所以当它被参数 stop 调用时,它不会停止监控。它只会启动另一个监控循环,永远不会终止。因为它是直接从关闭序列调用的,所以会阻止关闭终止。

编写 init.d 脚本的通常方法基于以下内容:

  • 当使用 start 选项调用时,脚本将服务(即您当前的监控脚本)作为守护进程启动,并将其 PID 写入名称与服务名称。 (放置此文件的常见位置是 /var/run 目录,通常扩展名为 .pid。)有一些标准实用程序可以将进程作为守护进程启动,这可以帮助完成这项任务。如果您有基于 Debian(包括 Ubuntu)的安装,请查看 shell 实用程序库 /lib/lsb/init-functions

  • 当使用 stop 选项调用时,脚本使用存储在 start 操作中创建的文件中的 PID 来kill过程。然后删除 pid 文件。

关于linux - Bash 脚本无限循环关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com