kill_port 0.1.3

Cross-platform utility to terminate processes by port efficiently. 跨平台高效终止端口进程工具。
Documentation

English | 中文


kill_port: Terminate processes by port efficiently

Table of Contents

Features

  • Cross-platform support: Works seamlessly on Unix-like systems and Windows
  • Smart process detection: Identifies processes listening on specific ports
  • Escalating termination: Graceful shutdown with SIGTERM, escalates to SIGKILL after 10 retries
  • Retry mechanism: Automatically retries with exponential backoff (500ms → 1000ms max)
  • Self-protection: Avoids terminating the calling process
  • Comprehensive logging: Detailed process termination tracking with retry counts

Installation

Add to your Cargo.toml:

[dependencies]
kill_port = "0.1.2"

Usage

Basic Usage

use kill_port::kill_port;

fn main() {
  // Terminate all processes listening on port 8080
  kill_port(8080);
}

With Logging

use kill_port::kill_port;
use log::info;

fn main() {
  env_logger::init();
  
  info!("Terminating processes on port 3000");
  kill_port(3000);
  info!("Port cleanup completed");
}

Design Philosophy

The library follows a progressive termination approach with intelligent retry logic:

graph TD
  A[kill_port called] --> B[Get current PID]
  B --> C[Query processes on port]
  C --> D{Processes found?}
  D -->|No| E[Exit]
  D -->|Yes| F[Filter out self]
  F --> G{Processes to kill?}
  G -->|No| E
  G -->|Yes| H[Kill processes]
  H --> I[Sleep with backoff]
  I --> C
  
  H --> J{Platform?}
  J -->|Unix| K{Retry > 10?}
  K -->|No| L[SIGTERM]
  K -->|Yes| M[SIGKILL]
  J -->|Windows| N[kill_tree]

Core Workflow

  1. Process Discovery: Uses listeners crate to identify processes bound to the target port
  2. Self-Protection: Filters out the current process to prevent self-termination
  3. Progressive Termination:
    • Unix: Starts with SIGTERM for graceful shutdown, escalates to SIGKILL after 10 retries
    • Windows: Uses kill_tree to terminate entire process trees
  4. Retry Logic: Implements exponential backoff with 500ms increments, capped at 1000ms
  5. Comprehensive Logging: Tracks termination attempts, retry counts, and signal types

Technical Stack

  • Core Language: Rust 2024 Edition
  • Process Detection: listeners - Cross-platform port listener detection
  • Unix Signals: nix - Safe Unix system call wrappers with signal escalation
  • Windows Process Management: kill_tree - Windows process tree termination
  • Logging: log - Structured logging interface

Project Structure

kill_port/
├── src/
│   └── lib.rs          # Main library implementation
├── tests/
│   └── main.rs         # Integration tests
├── readme/
│   ├── en.md          # English documentation
│   └── zh.md          # Chinese documentation
├── Cargo.toml         # Project configuration
└── test.sh           # Test script

API Reference

Functions

kill_port(port: u16)

Terminates all processes listening on the specified port with progressive escalation.

Parameters:

  • port: Target port number (1-65535)

Behavior:

  • Discovers processes bound to the port using listeners::get_processes_by_port
  • Excludes the calling process from termination list
  • Uses platform-appropriate termination methods with retry logic
  • Continues until all target processes are terminated
  • Logs detailed information including PID, process name, and retry count

Termination Strategy:

  • Unix:
    • Retries 1-10: SIGTERM for graceful shutdown
    • Retries 11+: SIGKILL for forceful termination
  • Windows: kill_tree terminates entire process trees immediately

Retry Logic:

  • Exponential backoff: min(retry * 500ms, 1000ms)
  • Continues indefinitely until port is clear
  • Each retry increments counter and adjusts sleep duration

Historical Context

The challenge of port-based process management has been persistent in software development. Early Unix systems relied on manual ps and kill commands, while Windows introduced taskkill for similar functionality.

Modern development environments, especially with microservices and hot-reloading development servers, frequently encounter port conflicts. Tools like lsof on Unix and netstat on Windows became essential for developers, but required platform-specific knowledge and complex command combinations.

The kill_port library emerged from the need for a unified, programmatic solution that abstracts platform differences while providing reliable process termination. The progressive escalation from SIGTERM to SIGKILL reflects decades of Unix process management best practices, ensuring both graceful shutdown opportunities and guaranteed termination for unresponsive processes.

This approach reflects the broader trend in systems programming toward safe, cross-platform abstractions that eliminate the need for platform-specific scripting while incorporating battle-tested process management strategies.


About

This project is an open-source component of js0.site ⋅ Refactoring the Internet Plan.

We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:


kill_port: 高效终止端口进程

目录

功能特性

  • 跨平台支持: 在类 Unix 系统和 Windows 上无缝运行
  • 智能进程检测: 识别监听特定端口的进程
  • 渐进式终止: 优雅关闭使用 SIGTERM,10 次重试后升级为 SIGKILL
  • 重试机制: 自动重试并采用指数退避策略(500ms → 1000ms 上限)
  • 自我保护: 避免终止调用进程本身
  • 全面日志: 详细的进程终止跟踪记录,包含重试次数

安装方法

Cargo.toml 中添加:

[dependencies]
kill_port = "0.1.2"

使用示例

基础用法

use kill_port::kill_port;

fn main() {
  // 终止所有监听 8080 端口的进程
  kill_port(8080);
}

带日志记录

use kill_port::kill_port;
use log::info;

fn main() {
  env_logger::init();
  
  info!("正在终止端口 3000 上的进程");
  kill_port(3000);
  info!("端口清理完成");
}

设计思路

库采用渐进式终止方法和智能重试逻辑:

graph TD
  A[调用 kill_port] --> B[获取当前 PID]
  B --> C[查询端口上的进程]
  C --> D{发现进程?}
  D -->|否| E[退出]
  D -->|是| F[过滤掉自身]
  F --> G{有进程需要终止?}
  G -->|否| E
  G -->|是| H[终止进程]
  H --> I[退避等待]
  I --> C
  
  H --> J{平台?}
  J -->|Unix| K{重试 > 10?}
  K -->|否| L[SIGTERM]
  K -->|是| M[SIGKILL]
  J -->|Windows| N[kill_tree]

核心工作流程

  1. 进程发现: 使用 listeners 库识别绑定到目标端口的进程
  2. 自我保护: 过滤掉当前进程以防止自我终止
  3. 渐进式终止:
    • Unix: 从 SIGTERM 优雅关闭开始,10 次重试后升级为 SIGKILL
    • Windows: 使用 kill_tree 终止整个进程树
  4. 重试逻辑: 实现指数退避,500ms 递增,上限 1000ms
  5. 全面日志: 跟踪终止尝试、重试次数和信号类型

技术栈

  • 核心语言: Rust 2024 版本
  • 进程检测: listeners - 跨平台端口监听器检测
  • Unix 信号: nix - 安全的 Unix 系统调用封装,支持信号升级
  • Windows 进程管理: kill_tree - Windows 进程树终止
  • 日志记录: log - 结构化日志接口

项目结构

kill_port/
├── src/
│   └── lib.rs          # 主要库实现
├── tests/
│   └── main.rs         # 集成测试
├── readme/
│   ├── en.md          # 英文文档
│   └── zh.md          # 中文文档
├── Cargo.toml         # 项目配置
└── test.sh           # 测试脚本

API 参考

函数

kill_port(port: u16)

使用渐进式升级策略终止所有监听指定端口的进程。

参数:

  • port: 目标端口号 (1-65535)

行为:

  • 使用 listeners::get_processes_by_port 发现绑定到端口的进程
  • 从终止列表中排除调用进程
  • 使用平台适当的终止方法和重试逻辑
  • 持续执行直到所有目标进程被终止
  • 记录详细信息,包括 PID、进程名和重试次数

终止策略:

  • Unix:
    • 重试 1-10 次: SIGTERM 优雅关闭
    • 重试 11+ 次: SIGKILL 强制终止
  • Windows: kill_tree 立即终止整个进程树

重试逻辑:

  • 指数退避: min(重试次数 * 500ms, 1000ms)
  • 无限重试直到端口清空
  • 每次重试递增计数器并调整睡眠时长

历史背景

基于端口的进程管理挑战在软件开发中一直存在。早期 Unix 系统依赖手动的 pskill 命令,而 Windows 引入了 taskkill 来实现类似功能。

现代开发环境,特别是微服务和热重载开发服务器,经常遇到端口冲突。Unix 上的 lsof 和 Windows 上的 netstat 等工具成为开发者必备,但需要平台特定知识和复杂的命令组合。

kill_port 库源于对统一编程解决方案的需求,该方案抽象了平台差异,同时提供可靠的进程终止功能。从 SIGTERMSIGKILL 的渐进式升级反映了数十年 Unix 进程管理最佳实践,既确保优雅关闭机会,又保证对无响应进程的强制终止。

这种方法反映了系统编程向安全、跨平台抽象的更广泛趋势,消除了平台特定脚本的需要,同时融入了经过实战检验的进程管理策略。


关于

本项目为 js0.site ⋅ 重构互联网计划 的开源组件。

我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注: