如何在 Composer 脚本中使用 timeout 来防止命令无限期执行?

admin 百科 19
Composer不支持脚本超时,需用系统工具实现:Linux/macOS用timeout或gtimeout命令,Windows用PowerShell的Start-Process加WaitForExit,跨平台可封装为独立脚本调用。

如何在 Composer 脚本中使用 timeout 来防止命令无限期执行?-第1张图片-佛山资讯网

Composer 本身不支持直接为脚本(scripts)设置执行超时,但可以通过操作系统命令包装器实现 timeout 控制,关键在于利用系统级 timeout 工具(Linux/macOS)或 PowerShell(Windows)来包裹实际命令。

Linux/macOS:用 timeout 命令包装脚本

composer.jsonscripts 段中,使用系统 timeout 命令限制运行时长。例如,限制 PHPUnit 测试最多运行 60 秒:

"scripts": {
  "test": "timeout 60 vendor/bin/phpunit --no-coverage"
}

登录后复制

注意:
- timeout 60 表示 60 秒后强制终止进程(发送 SIGTERM,可加 -k 发送 SIGKILL);
- 若命令提前完成,timeout 不影响结果;
- 确保系统已安装 GNU coreutils(macOS 需通过 brew install coreutils 安装 gtimeout,并改用 gtimeout 60)。

Windows:用 PowerShell 实现等效 timeout

Windows 默认无 timeout 命令,可用 PowerShell 的 Start-Process + -Wait -TimeoutSec 模拟:

"scripts": {
  "test": "powershell -Command "& { $p = Start-Process -FilePath 'vendor\\bin\\phpunit.bat' -ArgumentList '--no-coverage' -PassThru; if (!($p.WaitForExit(60000))) { $p.Kill(); exit 1 } }""
}

登录后复制

说明:
- WaitForExit(60000) 等待 60 秒(毫秒单位);
- 超时则调用 $p.Kill() 强制结束;
- exit 1 让 Composer 将其识别为失败,避免后续脚本继续执行。

跨平台兼容方案:封装成独立可执行脚本

为避免 composer.json 过于复杂,推荐将带超时逻辑的命令提取为外部脚本(如 bin/run-with-timeout),再在 scripts 中调用:

标签: php linux js json composer windows 操作系统 工具 mac ai macos win

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~