As an experienced AnQiCMS website operation manager, I know that precise management of the core application processes is crucial for the stable operation of the system in the production environment. Dependencyps -efSuch general commands for finding and managing processes are helpful in quickly locating issues, but their limitations become apparent in automation and high availability scenarios. Today, we will delve into how to adopt a more robust PID file management method in the deployment of AnQiCMS, and摆脱对ps -efThe imprecise dependency.
Farewellps -ef: Embrace a more reliable AnQiCMS process management
In the Linux system,ps -efThe command identifies running programs by matching process names. For applications like AnQiCMS written in Go, the default executable filename is usuallyanqicmsHowever, this kind of matching method based on name has inherent risks: if there are other processes with the name 'anqicms' in the system, or if different versions of AnQiCMS are running simultaneously,ps -efMay result in misjudgment, leading to incorrect start, stop, or restart operations. Particularly in script automation management, this uncertainty is unacceptable.
To achieve more accurate and reliable process management, the industry commonly adopts PID (Process ID) file mechanism.An PID file is a text file that contains only one number: the process ID of the main process of the application.When the application starts, it writes its PID to this file; when it closes normally, it deletes this file.In this way, our management script can directly read this file to obtain the accurate process ID, thus performing precise operations.
Introducing PID file management for AnQiCMS process
Considering the startup script of AnQiCMS (start.sh) Already exists, and is responsible for running the application as a background process; we can integrate PID file management seamlessly by modifying these scripts.This does not require modifying the AnQiCMS core code, but rather implementing it through the operating system's Shell script.
We first need to locate the installation directory of AnQiCMS. According to the documentation, this is usually located at/www/wwwroot/anqicmsor a similar path. Within this directory, you will findstart.shandstop.shthese two key scripts.
Step 1: Backup the existing start/stop scripts
Always make a backup before making any modificationsstart.shandstop.shThis ensures that you can easily recover if there are any issues. For example, you can copy them asstart.sh.bakandstop.sh.bak.
Step 2: Modifystart.shscript
We will modifystart.shMake sure to write the PID of the AnQiCMS process to a specified file after starting it. It is very important to choose a suitable PID file path, usually recommended to place it in/var/run/In the directory, or in the log directory of the application itself (for example)BINPATH/run/anqicms.pid).
The following is the modifiedstart.shExample:
#!/bin/bash
### check and start AnqiCMS
# author fesion
# the bin name is anqicms
BINNAME=anqicms
BINPATH=/www/wwwroot/anqicms # 请根据您的实际安装路径修改
PIDFILE=$BINPATH/run/$BINNAME.pid # 定义PID文件路径
# 确保PID文件所在的目录存在
mkdir -p $(dirname $PIDFILE)
echo "$(date +'%Y%m%d %H:%M:%S') $BINNAME PID check" >> $BINPATH/check.log
# 检查进程是否已在运行
if [ -f "$PIDFILE" ]; then
PID=$(cat "$PIDFILE")
if kill -0 "$PID" 2>/dev/null; then
echo "$BINNAME is already running with PID $PID" >> $BINPATH/check.log
echo "$BINNAME is already running with PID $PID"
exit 0
else
# PID文件存在但进程已不在,清除旧的PID文件
echo "Stale PID file found, removing $PIDFILE" >> $BINPATH/check.log
rm -f "$PIDFILE"
fi
fi
echo "$BINNAME NOT running, starting now..." >> $BINPATH/check.log
echo "$BINNAME NOT running, starting now..."
# 启动AnQiCMS并记录PID
cd $BINPATH && nohup $BINPATH/$BINNAME >> $BINPATH/running.log 2>&1 &
echo $! > "$PIDFILE" # 将新启动进程的PID写入PID文件
echo "$BINNAME started with PID $(cat "$PIDFILE")" >> $BINPATH/check.log
echo "$BINNAME started with PID $(cat "$PIDFILE")"
In this modification, we added aPIDFILESpecify the location of the PID file with a variable.Before starting, the script checks if this file exists and whether the recorded PID corresponds to a running process.If the PID file exists but the process has stopped, it will clean up the old PID file.echo $! > "$PIDFILE"The latest started background process PID will be written toPIDFILE.
Step 3: Modifystop.shscript
Correspondingly,stop.shThe script also needs to be modified so that it can read the process ID from the PID file and accurately terminate the AnQiCMS process.
#!/bin/bash
### stop anqicms
# author fesion
# the bin name is anqicms
BINNAME=anqicms
BINPATH=/www/wwwroot/anqicms # 请根据您的实际安装路径修改
PIDFILE=$BINPATH/run/$BINNAME.pid # 定义PID文件路径
echo "$(date +'%Y%m%d %H:%M:%S') $BINNAME PID check" >> $BINPATH/check.log
# 检查PID文件是否存在
if [ -f "$PIDFILE" ]; then
PID=$(cat "$PIDFILE")
if kill -0 "$PID" 2>/dev/null; then
echo "$BINNAME is running with PID $PID, stopping now..." >> $BINPATH/check.log
kill "$PID" # 发送SIGTERM信号,尝试优雅关闭
sleep 5 # 等待进程关闭
if kill -0 "$PID" 2>/dev/null; then
echo "$BINNAME did not stop gracefully, forcing kill $PID" >> $BINPATH/check.log
kill -9 "$PID" # 如果未能优雅关闭,则强制关闭
fi
rm -f "$PIDFILE" # 移除PID文件
echo "$BINNAME stopped and PID file removed." >> $BINPATH/check.log
echo "$BINNAME stopped."
exit 0
else
echo "Stale PID file found, process not running. Removing $PIDFILE" >> $BINPATH/check.log
rm -f "$PIDFILE" # PID文件存在但进程已停止,移除它
fi
else
echo "$PIDFILE not found. $BINNAME might not be running or PID file is missing." >> $BINPATH/check.log
echo "$PIDFILE not found. $BINNAME might not be running."
fi
In this modification,stop.shFirst, checkPIDFILEDoes it exist. If it exists, it will read the PID from it and usekillTerminate the corresponding process with a command.To ensure the robustness of the service, this includes the logic for graceful shutdown (SIGTERM) and forced shutdown (SIGKILL), and the PID file will be deleted after a successful stop to ensure a clean state for the next startup.
Step 4: Update the scheduled task or service management
If your AnQiCMS is throughcrontab -eThe scheduled tasks to maintain its running status, and these modifications will take effect automatically when the next execution occurs. Similarly, if you use Systemd or other service managers to start AnQiCMS, you also need to ensure that the service definition file inExecStartandExecStopThe command points to the one you modifiedstart.shandstop.shscript.
The advantages of using a PID file for management
Through the above modifications, your AnQiCMS process management will achieve the following significant improvements:
- High-precision recognition:Say goodbye to fuzzy matching based on names, directly operate through process ID to eliminate incorrect operations.
- Avoid zombie processes:The startup script checks for outdated PID files and cleans them up, reducing the situation where PID files remain after abnormal shutdowns and hinder normal startup.
- Improve automation reliability:In automated deployment and operation scripts, ensuring that each operation acts on the correct process greatly enhances the robustness of the system.
- Clear process status:The existence of the PID file can directly reflect the running status of the application, which is convenient for quick diagnosis.
By making these detailed adjustments, your AnQiCMS operating environment will become more professional and stable, giving you, as an operator, greater control over the system status.
Common Questions and Answers (FAQ)
1. If the AnQiCMS process crashes unexpectedly, will the PID file be automatically cleared?
No. Usually, it's only executed explicitly by the script.rm -f "$PIDFILE"Command, or the application itself, will delete the PID file only after receiving an exit signal and processing it normally.If the process crashes unexpectedly (for example, due to uncaught errors or system resource exhaustion), the PID file is likely to remain.start.shThe script has considered this situation: it checks whether the process ID recorded in the PID file is still active before starting.If the PID file exists but the corresponding process does not exist, it will be considered 'stale' and automatically cleaned up to ensure that the new process can start smoothly.
2. Where can I place the PID file? BesidesBINPATH/run/Are there any other recommended locations?
Yes, you can choose other locations. Typically, the PID file is recommended to be placed in/var/run/In the directory, this is the directory specifically used to store runtime process information in the Linux system. However,/var/run/The directory will be cleared after the system restart, so if your application needs to start automatically after a restart, it may require additional Systemd configuration or re-creation of the directory in the startup script. Place the PID file in the installation directory of the application.run/Subdirectory ($BINPATH/run/It is a common alternative, as it is bound to the application, easy to manage, and does not require special system permissions when write access to the application directory is available.It is important to ensure that the selected path has appropriate write permissions and is easily accessible by script.
3. Why doesn't the AnQiCMS application itself create and manage the PID file at startup?
It is indeed more ideal for the application itself to manage the PID file, as it ensures that the PID file is precisely created and deleted when the application starts up and shuts down normally.However, this usually requires modifying the source code of the application, and for third-party out-of-the-box systems like AnQiCMS, ordinary users may not be able to directly modify its Go language source code.The Shell script solution provided here is an effective and general method to implement PID file management strategy without modifying the core code of AnQiCMS.If AnQiCMS future versions could directly support PID file path in its configuration, that would be a better integration method.[en] Until now, encapsulating through Shell scripts is the most feasible and reliable solution.