Laravel 用 Process 门面调用外部命令:超时、输出捕获与异步

未来之星2026-11-0517 次阅读

场景

有时候业务要调用 ffmpeg、wkhtmltopdf、git 之类的外部程序。Laravel 10 引入的 Process 门面把 Symfony Process 包成流畅 API,支持超时、同步/异步、输出捕获与失败断言,比自己拼 exec 安全得多。

同步调用并读取输出

use Illuminate\Support\Facades\Process;

$result = Process::run('git rev-parse HEAD');

if ($result->successful()) {
    $commit = trim($result->output());
    // 使用 commit 哈希
}

设置超时与工作时间目录

$result = Process::timeout(30)
    ->path(storage_path('app'))
    ->run('wkhtmltopdf report.html report.pdf');

if ($result->failed()) {
    logger()->error('pdf 生成失败: ' . $result->errorOutput());
}

异步执行与轮询

耗时任务可以异步启动,拿到句柄后按需等待或检查是否结束。

$process = Process::start('php artisan import:big-csv');

// 做点别的事
while ($process->running()) {
    // 轮询进度
    usleep(500000);
}

$pool = $process->wait();
echo $pool->output();

要点

  • 命令字符串支持数组形式 Process::run(['ffmpeg', '-i', $in, $out]),可避免 shell 注入。
  • 用 output() 取标准输出,errorOutput() 取错误流,二者分开更利于排查。
  • 通过 throw() 可在失败时直接抛异常,配合 Laravel 异常处理器统一收口。
  • 长时间任务建议放进队列里调用,别阻塞 Web 请求。
未

未来之星

文章作者

场景 有时候业务要调用 ffmpeg、wkhtmltopdf、git 之类的外部程序。Laravel 10 引入的 P...

分类
技术
发布时间
2026-11-05
字数
约 973 字
阅读
17 次