Does the `exists -eq 0` check in the AnQiCMS `start.sh` script cause a race condition in extreme high concurrency startup scenarios?

Calendar 👁️ 72

As an experienced website operation expert, I know that AnQiCMS (AnQiCMS) excels in providing high-efficiency content management solutions for small and medium-sized enterprises and self-media operators.It has won widespread praise for its high performance and many practical features brought by the Go language.However, even the most excellent system, its deployment and operation details are worth in-depth discussion.start.shin the scriptexists -eq 0Check if there is a race condition (Race Condition) problem under the extreme high concurrency startup scenario.

In-depth analysis of AnQiCMS'sstart.shscript

First, let's review the official AnQiCMS documentation providedstart.shscript snippet, which is usually used to check and start the AnQiCMS service under Linux:

#!/bin/bash
BINNAME=anqicms
BINPATH=/www/wwwroot/anqicms # 假设的AnQiCMS安装路径

# 检查进程是否存在
exists=`ps -ef | grep '\<anqicms\>' |grep -v grep |wc -l`
echo "$(date +'%Y%m%d %H:%M:%S') $BINNAME PID check: $exists" >> $BINPATH/check.log
echo "PID $BINNAME check: $exists"
if [ $exists -eq 0 ]; then
    echo "$BINNAME NOT running"
    cd $BINPATH && nohup $BINPATH/$BINNAME >> $BINPATH/running.log 2>&1 &
fi

The core logic of this script is very intuitive: it first tries to find all running processes in the system, then throughgrepfilter out the processes namedanqicms(and excludegrepIts process), finally usingwc -lCount the number of matched processes. If this number is0(i.e.),exists -eq 0), then the script considers AnQiCMS not running and will execute.nohup ... &The command starts the AnQiCMS service in the background.

This "check-start" mode is a common practice in many basic service management scripts, intended to ensure that the service can be automatically started when it is not running, for example, bycrontabA scheduled task periodically checks the service status.

The potential risk of race conditions

Then, under the extreme high concurrency startup scenario,exists -eq 0Does the check method cause a race condition? The answer is yes, there is such a potential risk.

Race condition refers to the situation where the correctness of the result depends on the order of specific events when multiple processes or threads are executing concurrently in thisstart.shIn the scenario of the script, the problem lies in the tiny but crucial time window between the 'check' and 'start' operations.

Imagine the following situation:

  1. Time T1:Assuming the AnQiCMS service on the system is currently stopped.
  2. At time T2:Multiple (such as two)start.shThe script instance almost starts executing at the same time. We call it Script A and Script B.
  3. At moment T3:Script A executes toexists=ps -ef … wc -l`这一行。由于AnQiCMS尚未运行,脚本A得到的exists值为0`.
  4. Moment T4:Script B also executes almost at the same momentexists=ps -ef … wc -l`这一行。由于脚本A还没有来得及启动AnQiCMS,脚本B同样得到的exists值为0`.
  5. Moment T5:Script A judgmentif [ $exists -eq 0 ]True, start executingnohup $BINPATH/$BINNAME ... &Start AnQiCMS service.
  6. Time T6:Before script A completes the startup of AnQiCMS and the operating system registers the new process (or even if it is registered, but script B'spsThe command has not been perceived, script B also judgesif [ $exists -eq 0 ]to be true, and then execute againnohup $BINPATH/$BINNAME ... &and try to start the AnQiCMS service.

Under this unfortunate timing, two (or more) AnQiCMS processes may be started simultaneously.For most server applications, especially content management systems like AnQiCMS, they are usually designed to run as a single instance to avoid port conflicts, data inconsistency, or resource contention issues.faq.mdandinstall.mdMentioned in the middle, running multiple AnQiCMS instances on the same server requires different ports, which indirectly indicates that AnQiCMS itself is usually not recommended to run multiple instances on the same port.

If two instances of AnQiCMS try to bind to the same port (such as the default 8001 port), the second instance to start may fail to start because the port is already occupied, and it may leave an error message in the log.The worse part is, if the system does not have strict port binding failure handling, or if the application design allows, it may lead to confusion in some functions, even one instance may become 'false dead', which undoubtedly brings unnecessary trouble and risk to the website operation.

Why is a simple check not enough?

The root cause of the occurrence of this race condition lies in the lack of native atomic operations and inter-process synchronization mechanisms in Unix/Linux shell scripts.ps -efQuerying process status andnohup ... &Between starting processes, it is not an atomic operation, there is a time difference. Within this time difference, the system state may change, causing the initial check result to no longer be valid.

AnQiCMS is a system developed based on the Go language, which may internally use mechanisms such as Goroutine to achieve efficient concurrent processing and has excellent high concurrency performance. But please note that the race condition problem does not lie in the concurrent design of the AnQiCMS application itself, but exists in the management of its lifecycle.External shell scriptLevel.

Relieve and **practice

To avoid this race condition in the startup script, the following more robust strategies can be adopted:

  1. Use file locks (flockOr Pid file locked:

    • flockCommand:Instart.shAt the beginning of the script useflockThe command creates a file lock. If the lock is held by another script instance, the current script will wait or exit directly.bash #!/bin/bash LOCKFILE="/var/lock/anqicms_start.lock" exec 200>$LOCKFILE flock -n 200 || exit 1 # -n表示非阻塞,如果不能获取锁则立即退出 # 或者 flock 200 # 阻塞等待,直到获取锁 BINNAME=anqicms BINPATH=/www/wwwroot/anqicms exists=ps -ef | grep 'canqicms' |grep -v grep |wc -l if [ $

Related articles

How to add a delay in the `start.sh` script of AnQiCMS to ensure that the port is completely released before starting?

## Ensure AnQiCMS graceful restart: Add a delay mechanism in the `start.sh` script AnQiCMS provides strong support for content operators with its efficient and concise features developed based on the Go language.Its deployment is simple and execution is fast, making content management and website operations smooth and easy.However, even such a high-performance system, in certain specific O&M scenarios, such as frequent restarts, updates and deployments, or when the server resources are tight, you may accidentally encounter a pesky problem: the program fails to start

2025-11-06

When starting the AnQiCMS process, besides PID check, what are the critical prerequisite conditions that need to be verified?

As an experienced website operations expert, I know that a stable and efficient website system cannot be separated from its rigorous startup process and preconditions verification.AnQiCMS is an enterprise-level content management system developed based on the Go language, which has won wide recognition for its lightweight and efficient features.Even though its startup mechanism is quite robust, for example, we all understand that AnQiCMS first performs a PID check during startup, which is a basic protection mechanism aimed at preventing the same instance from running repeatedly and ensuring the reasonable allocation of system resources.But except for this basic "authentication"

2025-11-06

If the server resources are tight, how will the PID log show when the AnQiCMS process is killed by the system OOM (Out Of Memory)?

As an experienced website operations expert, I am well aware that the health of server resources is crucial for the stable operation of a CMS system, especially for systems like AnQiCMS that focus on high performance and concurrent processing.When server resources, especially memory, become tight, the system kernel may terminate those processes that use too much memory without hesitation to maintain overall stability, which is what we often call the 'OOM (Out Of Memory) kill' process.Then, when the AnQiCMS process is unfortunately killed by the system OOM

2025-11-06

How to configure AnQiCMS to automatically write the PID to a specified file when it starts?

As a website operator familiar with AnQiCMS, I am well aware of the importance of system stability and convenient management.AnQiCMS as an excellent content management system developed based on the Go language, has won our trust with its high performance and simple architecture.In daily operations and maintenance, effective management of background processes is the key to ensuring that the website remains online.The use of the process ID (PID) file greatly simplifies the operations of starting, stopping, and checking the status of AnQiCMS services.###

2025-11-06

How to quickly view the root directory path of the current AnQiCMS installation?

As an experienced website operations expert, I am well aware that clearly understanding the file structure and critical path of AnQiCMS website is of great importance when managing and maintaining it.Especially when adjusting configurations, modifying templates, troubleshooting, or managing multiple sites, quickly locating the root directory path of AnQiCMS can greatly enhance our work efficiency.AnQiCMS is a modern content management system developed based on the Go language, with flexible and diverse deployment methods, ranging from running directly on the server to managing through panels such as Baota, 1Panel, and containerized deployment

2025-11-06

Where is the default directory for storing AnQiCMS template files?

## Unveiling the Location of AnQiCMS Template Files: Default Directory Depth Analysis When building and operating a website with AnQiCMS, template files are the core that determines the appearance and interaction of the website.Whether it is to carry out personalized customization, fault diagnosis, or secondary development, clearly understanding the storage location of the template files is the first step.Where is the default template file stored for AnQiCMS?The answer is the `/template` directory. ###

2025-11-06

Where should the static resources such as CSS, JS, and images used by the website front-end be placed?

As an experienced website operations expert, I am well aware that the reasonable management of website front-end static resources is crucial for website performance, maintenance convenience, and even search engine optimization (SEO).AnQiCMS (AnQiCMS) took this into full consideration from the very beginning of the system design, providing developers and operators with a clear and efficient path for resource management.Today, let's delve into the discussion of where to place the CSS, JS, and image static resources used on your website's front end in AnQiCMS, in order to achieve the most reasonable and efficient practice.

2025-11-06

How to find and edit the template folder being used by the current site in AnQiCMS?

As an experienced website operations expert, I know that mastering the positioning and editing methods of templates like AnQiCMS, which is a flexible and efficient content management system, is a key step to achieving website personalization, enhancing user experience, and optimizing SEO.AnQiCMS with its lightweight and high-performance Go language provides us with a solid foundation, and its powerful template customization capabilities give content operators unlimited possibilities.Today, let's delve into how to accurately find and edit the template folder currently in use on the AnQiCMS website

2025-11-06