Skip to content

fix(server): add O_TRUNC when creating PID file to avoid stale content - #3598

Open
weim0000 wants to merge 1 commit into
apache:unstablefrom
weim0000:fix_pid
Open

fix(server): add O_TRUNC when creating PID file to avoid stale content#3598
weim0000 wants to merge 1 commit into
apache:unstablefrom
weim0000:fix_pid

Conversation

@weim0000

Copy link
Copy Markdown
Contributor

What problem does this change solve?

CreatePidFile opens the PID file with O_RDWR | O_CREAT but without O_TRUNC. If a stale PID file already exists from a previous run and the old PID string is longer than the new one, open() + write() will only overwrite the first N bytes of the file, leaving the trailing bytes from the old content intact. This results in a corrupted PID file.

Example:
Step File content Note
Previous run (PID=12345) 12345 correct
New run (PID=678), without O_TRUNC 67845 corrupted — trailing 45 is stale
New run (PID=678), with O_TRUNC 678 correct

A corrupted PID file can cause process management tools (e.g., kill $(cat pidfile), systemd, init scripts) to target the wrong process or fail to stop/restart the service.

How does this change fix the problem?

Add O_TRUNC to the open() flags in CreatePidFile so the file is truncated to zero length before writing the new PID, ensuring no stale bytes remain.

Changes

  • src/cli/pid_util.h: Add O_TRUNC flag to the open() call in CreatePidFile.
  • tests/cppunit/pid_util_test.cc: Add unit tests covering:
    • Truncation on existing file: Write a longer fake PID first, then call CreatePidFile and verify the content matches exactly the current PID with no leftover bytes.
    • Creation from scratch: Verify CreatePidFile works correctly when no file exists.
    • RemovePidFile: Verify the PID file is properly removed.

@github-actions

Copy link
Copy Markdown

Hi @weim0000,

Thank you for your pull request. Please review our Contributing Guide.

Please make sure you understand your changes and explain your reasoning in this pull request. Low-quality pull requests may be closed.

@PragmaTwice
PragmaTwice requested a review from git-hulk August 25, 2026 16:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant