我有一个 cron 作业,每隔几秒就会生成与父进程同名的子进程。所有的 CPU 使用率都在子进程上持续几秒钟,然后就消失了。看起来真的很奇怪。以下是 htop 的输出:
CPU% MEM% Command
0 0 /bin/sh -c /etc/script.sh > /var/log/script.log
0 0 |— /bin/bash /etc/script.sh
100 0.4 |— /bin/bash /etc/script.sh
最后一个进程每隔几秒就会重新生成一次。为什么它不在一个进程下运行?子进程命令是否应该更像我从脚本运行的实际命令,例如:|-- find .. / 或 / |-- grep 或 |-- tar ?
计划任务:
*/30 * * * * root /etc/script.sh > /var/log/script.log
脚本:
#!/bin/bash
LOG_DIR={{ log_dir | default('/var/logs') }}
ARCHIVE_DIR={{ archive_dir | default('/var/archive') }}
PIDFILE={{ pidfile | default('/run/script.pid') }}
## Handle cases where cronjobs take too long to prevent starting new ones
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "Process already running"
exit 1
else
## Process not found assume not running
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
else
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
new_files_archived=0
for folder in $(ls ${LOG_DIR});
do
## Archive the last 30 days worth of logs
log_files=$(find -H ${LOG_DIR}/${folder} -not -empty -type f -regex '.*.log' -mtime -5)
archived_logs_files=$(find ${ARCHIVE_DIR/$folder} -type f)
if [ $? -eq 0 ]; then
mkdir -p "$ARCHIVE_DIR/$folder"
fi
for log_file in $log_files;
do
grep -q $(basename ${log_file} .log) <<<$archived_logs_files
if [ $? -eq 0 ]; then
:
#echo $log_file Found, already archived, skipping..
else
echo ${log_file}.gz Not Found, creating archive
gzip -c $log_file > "$ARCHIVE_DIR/$folder/$(basename ${log_file}).gz"
touch -d "$(date -R -r ${log_file})" "$ARCHIVE_DIR/$folder/$(basename ${log_file}).gz"
let new_files_archived++
fi
done;
done;
echo $new_files_archived new files added to archive
## Remove file lock after executing
rm $PIDFILE
答案1
脚本文件是否标记为可执行文件,即“x”?所有者是谁?root 还是普通用户?
我个人更喜欢限定命令,即提供完整的路径,例如 find so:
LOG_FILES=$(/bin/find -H ${LOG_DIR}/${folder} -not -empty -type f -name '*.log' -mtime -5)
使用名称而不是正则表达式,因为在这种情况下正则表达式不提供任何更多功能。特别是因为正则表达式“。”匹配将匹配任何字符,因此它将匹配您可能不想要的“helloslog”。