2.3 启动 Gateway 守护进程

生成模型:Claude Opus 4.6 (anthropic/claude-opus-4-6) Token 消耗:输入 ~140,000 tokens,输出 ~10,000 tokens(本章合计)


Gateway 是 OpenClaw 的核心进程——它必须持续运行,才能接收和处理来自各个通道的消息。本节介绍如何启动 Gateway,以及 OpenClaw 如何实现守护进程管理。

2.3.1 前台启动 vs 守护进程模式

前台启动

最简单的启动方式是在终端前台运行:

# 前台启动 Gateway
openclaw gateway --port 18789 --verbose

# 或者从源码运行
pnpm openclaw gateway --port 18789 --verbose

前台模式下,Gateway 直接在当前终端运行,日志输出到 stdout。关闭终端或按 Ctrl+C 会停止 Gateway。这种模式适合开发和调试。

守护进程模式

在生产环境中,你希望 Gateway 在后台持续运行,并在系统重启后自动启动。OpenClaw 通过系统原生的服务管理工具实现这一点:

  • macOS:launchd(launchctl

  • Linux:systemd(systemctl

  • Windows:计划任务(Task Scheduler,通过 schtasks

安装守护进程:

2.3.2 launchd / systemd 服务安装的源码分析

守护进程管理的源码位于 src/daemon/ 目录(30 个文件),按操作系统平台分为几个模块:

macOS:launchd 服务

在 macOS 上,OpenClaw 生成一个 launchd plist 文件并安装为用户级服务。src/daemon/launchd-plist.ts 负责生成这个 XML 配置:

关键配置:

  • RunAtLoad:系统启动时自动运行

  • KeepAlive:进程崩溃后自动重启

src/daemon/launchd.ts 封装了 launchctl 命令的调用(loadunloadlist 等),提供安装、卸载、重启等操作。

Linux:systemd 用户服务

在 Linux 上,OpenClaw 生成一个 systemd user unit 文件。src/daemon/systemd-unit.ts 负责生成:

由于是用户级服务(~/.config/systemd/user/),不需要 root 权限即可安装和管理。src/daemon/systemd-linger.ts 处理了 loginctl enable-linger 配置,确保用户服务在用户未登录时也能运行。

Windows:计划任务

在 Windows 上(需要 WSL2),src/daemon/schtasks.ts 使用 schtasks.exe 创建计划任务。由于 OpenClaw 强烈推荐在 WSL2 中运行,Windows 原生的计划任务主要用于在系统启动时自动启动 WSL 中的 Gateway。

统一的服务管理接口

src/daemon/service.ts 提供了跨平台的统一接口:

无论底层使用 launchd、systemd 还是 schtasks,上层代码(CLI 命令 openclaw daemon install/start/stop)都通过这个统一接口操作。

守护进程的生命周期管理

安装完成后,Gateway 会在后台持续运行。你可以通过以下方式验证:

openclaw doctor 是一个综合诊断命令,会检查:

  • Gateway 进程是否运行

  • 端口是否可达

  • 配置文件是否有效

  • 通道连接状态

  • 模型认证状态

  • 安全配置是否合理

当一切正常时,你的个人 AI 助手就已经在后台运行了。接下来让我们看看如何高效地进行开发。

Last updated