网关锁
Gateway 使用锁文件(Lock File)机制确保同一数据目录下只有一个 Gateway 实例运行,防止数据竞争和端口冲突。
工作原理
text
Gateway 启动流程:
1. 检查锁文件是否存在
├─ 不存在 → 创建锁文件 → 启动
└─ 存在 → 检查持有者 PID
├─ PID 仍在运行 → 启动失败(已有实例运行)
└─ PID 已不存在 → 删除过期锁 → 创建新锁 → 启动
2. Gateway 运行中持续持有锁
3. Gateway 停止时删除锁文件锁文件位置
| 平台 | 路径 |
|---|---|
| macOS / Linux | ~/.openclaw/gateway.lock |
| Windows | %USERPROFILE%\.openclaw\gateway.lock |
锁文件内容
锁文件包含当前运行实例的元信息:
json
{
"pid": 42187,
"port": 18789,
"host": "127.0.0.1",
"startedAt": "2025-01-15T10:30:00Z",
"version": "0.5.0"
}常见场景
正常启动
bash
$ openclaw gateway
[INFO] Lock acquired: ~/.openclaw/gateway.lock (PID: 42187)
[INFO] Gateway started on 127.0.0.1:18789重复启动
bash
$ openclaw gateway
[ERROR] Another gateway instance is already running
PID: 42187
Port: 18789
Since: 2025-01-15 10:30:00
Use 'openclaw status' to check the running instance.
Use 'openclaw gateway stop' to stop it first.过期锁(异常退出后)
如果 Gateway 因崩溃、断电等原因异常退出,锁文件可能未被正常清理:
bash
$ openclaw gateway
[WARN] Stale lock file detected: PID 98765 is not running
[INFO] Removing stale lock file
[INFO] Lock acquired: ~/.openclaw/gateway.lock (PID: 42188)
[INFO] Gateway started on 127.0.0.1:18789自动清理
Gateway 启动时会自动检测过期锁文件(持有者 PID 已不存在),并自动清理后继续启动。
手动解锁
在极少数情况下,可能需要手动删除锁文件:
bash
# 查看锁文件内容
openclaw gateway lock-info
# 强制解锁
openclaw gateway unlock输出:
text
Lock file: ~/.openclaw/gateway.lock
PID: 42187
Status: process not running (stale)
Port: 18789
Started: 2025-01-15 10:30:00
Remove stale lock? [y/N]: y
Lock removed successfully.谨慎解锁
在手动解锁前,确认没有 Gateway 实例正在运行。强制解锁运行中的实例可能导致数据损坏。
强制解锁(不询问)
bash
# 不询问直接解锁
openclaw gateway unlock --force危险操作
--force 会跳过所有安全检查,直接删除锁文件。仅在确认没有运行中实例时使用。
多实例运行
如果确实需要运行多个 Gateway 实例(如不同项目),需要使用不同的数据目录:
bash
# 实例 1:默认数据目录
openclaw gateway --port 18789
# 实例 2:自定义数据目录(不同的锁文件)
openclaw gateway --port 18790 --data-dir ~/.openclaw-dev每个数据目录有独立的锁文件,互不冲突。
详见 多网关部署。
Doctor 诊断
openclaw doctor 会自动检查锁文件状态:
bash
openclaw doctor --check locktext
✓ No stale lock files
Current lock: PID 42187 (running)
Port: 18789故障排查
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 启动失败:已有实例运行 | 同一目录下已有 Gateway | openclaw gateway stop 停止后重启 |
| 启动失败:端口被占用 | 其他程序占用端口 | 换端口 --port 18790 或停止占用进程 |
| 过期锁未自动清理 | PID 回绕导致误判 | openclaw gateway unlock 手动解锁 |
| 权限错误 | 锁文件权限不正确 | 检查数据目录权限 |
