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

Composer 本身不支持直接为脚本(scripts)设置执行超时,但可以通过操作系统命令包装器实现 timeout 控制,关键在于利用系统级 timeout 工具(Linux/macOS)或 PowerShell(Windows)来包裹实际命令。
在 composer.json 的 scripts 段中,使用系统 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 默认无 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 中调用:
bin/run-with-timeout 60 vendor/bin/phpunit
bin\run-with-timeout.ps1 60 vendor\bin\phpunit.bat
"test": "bin/run-with-timeout 60 vendor/bin/phpunit"(Composer 会自动适配平台)这样既保持配置简洁,又便于测试和调试超时行为。
基本上就这些。核心是绕过 Composer 自身限制,借助宿主系统能力做进程管控 —— 不复杂但容易忽略。
以上就是如何在 Composer 脚本中使用 timeout 来防止命令无限期执行?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号