How to customize the PID path of AnQiCMS process instead of depending on `ps -ef`?

Calendar 👁️ 51

As an experienced AnQiCMS website operator, I know that accurate management of core application processes is the key to stable operation in the production environment. Dependencyps -efSuch a general command to search and manage processes, although it helps in quickly locating problems, its limitations are evident in automation and high availability scenarios. Today, let's delve into how to adopt a more robust PID file management method in the deployment of AnQiCMS, and摆脱对ps -efinaccurate dependency.

farewellps -ef: Embrace the more reliable AnQiCMS process management

in the Linux system,ps -efThe command identifies running programs by matching process names. For Go language applications like AnQiCMS, the default executable file name is usuallyanqicmsHowever, this kind of matching 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 -efThere may be misjudgment, leading to incorrect start, stop, or restart operations. Especially in script automation management, this uncertainty is unacceptable.

To achieve more accurate and reliable process management, the industry commonly adopts the PID (Process ID) file mechanism.A PID file is a text file that contains a single number: the process ID of the main application process.When the application starts, it writes its PID to this file;When it is closed normally, it will delete this file. In this way, our management script can directly read this file to obtain the accurate process ID, thereby 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 modify these scripts to seamlessly integrate PID file management.This does not require modifying the AnQiCMS core code, but rather implementing it through the operating system's Shell scripts.

We first need to locate the installation directory of AnQiCMS. According to the documentation, it is usually located in/www/wwwroot/anqicmsor a similar path. In this directory, you will findstart.shandstop.shthese two key scripts.

First step: Backup the existing start/stop script

Be sure to backup before making any modificationsstart.shandstop.shThis ensures that you can easily recover if there are any problems. For example, you can copy them asstart.sh.bakandstop.sh.bak.

Second step: Modifystart.shscript

We will modifystart.shTo make it write the PID to a specified file after starting the AnQiCMS process. Choosing an appropriate PID file path is very important, usually it is recommended to place it in/var/run/In the directory, or in the log directory of the application (for example)BINPATH/run/anqicms.pid)

The following has been 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 onePIDFILEThe variable is used to specify the location of the PID file. Before starting, the script will check if the file exists and whether the PID recorded in it corresponds to a running process.If the PID file exists but the process has stopped, it will clean up the old PID file.AnQiCMS launched,echo $! > "$PIDFILE"Will write the PID of the latest started background process toPIDFILE.

The third step: 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 and usekillCommand to terminate the corresponding process. To ensure the robustness of the service, it includes the logic of graceful shutdown (SIGTERM) and forced shutdown (SIGKILL), and will delete the PID file after successful shutdown 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 task to maintain its running status, then these changes will take effect automatically the next time it runs. Similarly, if you use Systemd or another service manager to start AnQiCMS, you also need to ensure that the service definition file inExecStartandExecStopThe command points to the modified one youstart.shandstop.shscript.

Advantages of using PID file management

With the above modifications, your AnQiCMS process management will achieve the following significant improvements:

  1. High-precision recognition:Said goodbye to fuzzy matching based on name, directly operate through process ID, eliminating incorrect operations.
  2. Avoid zombie processes:The startup script checks and cleans old PID files, reducing the situation where PID files remain due to abnormal shutdown and hinder normal startup.
  3. Improve automation reliability:In automated deployment and operation scripts, it ensures that each operation acts on the correct process, greatly enhancing the robustness of the system.
  4. Clear process status:The existence or absence of the PID file can directly reflect the running status of the application, making it easy 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.


Frequently Asked Questions (FAQ)

1. If the AnQiCMS process crashes unexpectedly, will the PID file be automatically deleted?

No. Generally speaking, it is only executed explicitly by the script.rm -f "$PIDFILE"The command, or the application itself, will only delete the PID file after receiving a termination signal and processing it normally.If a process crashes unexpectedly (for example, due to an uncaught error or system resource exhaustion), the PID file may remain.However, we have modified it.start.shThe script has considered this situation: it will check if 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 besides?BINPATH/run/Are there any other recommended locations?

Yes, you can choose another location. Typically, it is recommended to place the PID file in/var/run/In the directory, this is the directory 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, you may need additional Systemd configuration or to recreate the directory in the startup script. Place the PID file in the installation directory of the application.run/subdirectory ($BINPATH/run/) is a common alternative because it is bound to the application, easy to manage, and does not require special system permissions when the application directory has write permissions.It is important to ensure that the selected path has appropriate write permissions and is easy for script access management.

3. Why should not the AnQiCMS application itself create and manage the PID file at startup?

It is indeed a better practice for the application to manage the PID file itself, as it ensures that the PID file is accurately created and deleted when the application starts and closes 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 we provide here is an effective and general method to implement PID file management strategy without modifying the core code of AnQiCMS.If the future version of AnQiCMS can directly support the PID file path in its configuration, it will be a better integration method.Prior to this, encapsulating through Shell scripts is the most feasible and reliable solution available.

Related articles

AnQiCMS process crashed under high load, what clues can the PID check log provide?

As a website operator who has been deeply involved in AnQiCMS (AnQiCMS) for many years, I know that in the face of stability challenges under high system load, logs are our most loyal partners.When the AnQiCMS process crashes unfortunately under high load, the `PID` check log, especially the `check.log`, can provide us with key preliminary clues to guide us in deeper problem diagnosis.

2025-11-06

Will the AnQiCMS process still exist if it is started without `nohup` and the terminal is closed? Is this related to PID?

AnQiCMS is a high-performance enterprise-level content management system developed based on the Go language, its core lies in providing stable and efficient content management services.It is crucial to ensure that any long-running server-side application, such as AnQiCMS, can continue to run stably after startup, even if the terminal session that launched it is closed.

2025-11-06

Why does the AnQiCMS `stop.sh` script use `awk '{printf $2}'` after `grep` to get the PID?

In the operation and maintenance of AnQi CMS, we often encounter situations where we need to start or stop services.For the AnQiCMS project developed based on the Go language, it usually runs as a single binary executable file.To achieve smooth service management, the `stop.sh` script plays a core role.

2025-11-06

How to add a more robust PID file management mechanism to the AnQiCMS startup script?

As an experienced Anqi CMS website operation person, I know that the stability and reliability of website services are the foundation for the success of content operation.AnQiCMS with its efficient Go language features and concise architecture provides us with a solid foundation, but ensuring the robustness of its startup and shutdown in actual deployment, especially process management, is the key link that requires refined polishing.

2025-11-06

Is the logic in the `start.sh` script of AnQiCMS `if [ $exists -eq 0 ];` strict enough and prone to misjudgment?

As an experienced CMS website operation personnel of an enterprise, I am well aware of the importance of system stability and content publishing efficiency to the business.In the daily operation and maintenance of AnQiCMS, the `start.sh` script is a key link to ensure the continuous operation of the service.Among the logic of `if [ $exists -eq 0 ];`, although it seems simple, it carries the core responsibilities of service health check and automatic startup.Today, let's delve into the rigor of this logic and the potential risk of 'misjudgment'.

2025-11-06

After upgrading AnQiCMS, will the PID of the old process be automatically updated, or do I need to handle it manually?

As an experienced operator of AnQi CMS, I am well aware of the importance of system upgrades for maintaining website security and advanced functionality.When performing an AnQiCMS upgrade, many users may have a core question: Will the old program process identifier (PID) be automatically updated after the upgrade?Or should we manually intervene? AnQiCMS is an enterprise-level content management system developed based on the Go programming language, one of its core features is to run as a standalone binary executable file.This means when you start AnQiCMS

2025-11-06

What changes in the PID check and management logic when deploying AnQiCMS in the Docker environment?

In the operation practice of AnQi CMS, efficient content creation, publishing, and optimization are the core, but the guarantee of stable system operation is also indispensable.This is an important link in system maintenance, checking and managing the process (PID).When AnQi CMS migrates from the traditional server deployment environment to the Docker containerized environment, this underlying PID management logic will undergo a fundamental change, which is crucial for website operators to understand and troubleshoot problems.

2025-11-06

If the AnQiCMS process cannot be terminated with `kill -9`, could it be related to the PID?

As a senior CMS website operation personnel of a well-known security company, I know that process control is a key link in maintaining the stable operation of the website in daily management.When encountering a situation where it is necessary to forcibly terminate the AnQiCMS process but the `kill -9` command seems to be ineffective, this is indeed a headache.Below, I will elaborate on the possible reasons from my experience and discuss the role of process ID (PID) in it.

2025-11-06