프로세스
업데이트됨번역일: 2026년 6월 25일
이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.
- 원문 수정
- 2026년 6월 20일
- 번역 갱신
- 2026년 6월 25일
프로세스
소개
Laravel은 Symfony Process 컴포넌트를 기반으로 외부 프로세스를 간결하게 실행할 수 있는 API를 제공합니다. 가장 일반적인 사용 사례에 집중하면서도 개발자 경험을 최우선으로 설계되어 있습니다.
프로세스 실행
프로세스를 실행하려면 Process 파사드의 run 또는 start 메서드를 사용합니다. run은 프로세스를 동기적으로 실행하고 완료될 때까지 기다리며, start는 비동기적으로 실행합니다. 먼저 동기 방식부터 살펴보겠습니다.
use Illuminate\Support\Facades\Process;
$result = Process::run('ls -la');
return $result->output();run 메서드는 Illuminate\Contracts\Process\ProcessResult 인스턴스를 반환하며, 이를 통해 실행 결과를 다양한 방법으로 확인할 수 있습니다.
$result = Process::run('ls -la');
$result->command(); // 실행된 명령어
$result->successful(); // 성공 여부
$result->failed(); // 실패 여부
$result->output(); // 표준 출력 (stdout)
$result->errorOutput(); // 표준 에러 (stderr)
$result->exitCode(); // 종료 코드예외 던지기
프로세스가 실패했을 때(종료 코드가 0보다 클 때) 자동으로 예외를 던지려면 throw 또는 throwIf 메서드를 사용하세요. 프로세스가 성공한 경우에는 ProcessResult 인스턴스가 그대로 반환됩니다.
$result = Process::run('ls -la')->throw();
$result = Process::run('ls -la')->throwIf($condition);실패 시 Illuminate\Process\Exceptions\ProcessFailedException 예외가 발생합니다.
프로세스 옵션
프로세스를 실행하기 전에 작업 디렉터리, 타임아웃, 환경 변수 등 다양한 동작을 설정할 수 있습니다.
작업 디렉터리 지정
path 메서드로 프로세스의 작업 디렉터리를 지정할 수 있습니다. 지정하지 않으면 현재 PHP 스크립트가 실행 중인 디렉터리를 상속합니다.
$result = Process::path(__DIR__)->run('ls -la');표준 입력(stdin) 제공
input 메서드를 사용하면 프로세스의 표준 입력으로 데이터를 전달할 수 있습니다.
$result = Process::input('안녕하세요')->run('cat');타임아웃
기본적으로 프로세스가 60초를 초과하면 Illuminate\Process\Exceptions\ProcessTimedOutException이 발생합니다. timeout 메서드로 이 값을 변경할 수 있습니다.
$result = Process::timeout(120)->run('bash import.sh');timeout과 idleTimeout 메서드는 CarbonInterval 인스턴스도 받을 수 있습니다.
use function Illuminate\Support\minutes;
$result = Process::timeout(minutes(2))->run('bash import.sh');타임아웃을 완전히 비활성화하려면 forever 메서드를 사용하세요.
$result = Process::forever()->run('bash import.sh');idleTimeout은 프로세스가 일정 시간 동안 아무 출력도 내보내지 않을 때 타임아웃을 발생시킵니다. 예를 들어 아래 설정은 전체 실행 60초, 출력이 없는 상태로 30초가 지나면 타임아웃이 됩니다.
$result = Process::timeout(60)->idleTimeout(30)->run('bash import.sh');환경 변수
env 메서드로 프로세스에 환경 변수를 전달할 수 있습니다. 시스템에 이미 정의된 환경 변수는 자동으로 상속됩니다.
$result = Process::forever()
->env(['IMPORT_PATH' => __DIR__])
->run('bash import.sh');상속된 환경 변수를 제거하려면 값으로 false를 전달하세요.
$result = Process::forever()
->env(['LOAD_PATH' => false])
->run('bash import.sh');TTY 모드
tty 메서드를 사용하면 TTY 모드를 활성화하여 프로세스의 입출력을 현재 터미널과 연결할 수 있습니다. Vim이나 Nano 같은 대화형 에디터를 프로세스로 실행할 때 유용합니다.
Process::forever()->tty()->run('vim');WARNING
TTY 모드는 Windows에서 지원되지 않습니다.
프로세스 출력
앞서 살펴본 것처럼 output(stdout)과 errorOutput(stderr) 메서드로 실행 결과를 확인할 수 있습니다.
use Illuminate\Support\Facades\Process;
$result = Process::run('ls -la');
echo $result->output();
echo $result->errorOutput();출력을 실시간으로 처리하려면 run 메서드의 두 번째 인자로 클로저를 전달하세요. 클로저는 출력 타입(stdout 또는 stderr)과 출력 문자열을 인자로 받습니다.
$result = Process::run('ls -la', function (string $type, string $output) {
echo $output;
});특정 문자열이 출력에 포함되어 있는지 확인할 때는 seeInOutput과 seeInErrorOutput 메서드를 활용할 수 있습니다.
if (Process::run('ls -la')->seeInOutput('laravel')) {
// ...
}출력 비활성화
대량의 출력이 발생하지만 결과가 필요하지 않다면 quietly 메서드로 출력 수집을 비활성화하여 메모리를 절약할 수 있습니다.
use Illuminate\Support\Facades\Process;
$result = Process::quietly()->run('bash import.sh');파이프라인
한 프로세스의 출력을 다른 프로세스의 입력으로 연결하는 Unix 파이프(|)와 동일한 기능을 pipe 메서드로 구현할 수 있습니다. 파이프라인의 모든 프로세스는 동기적으로 실행되며, 마지막 프로세스의 결과가 반환됩니다.
use Illuminate\Process\Pipe;
use Illuminate\Support\Facades\Process;
$result = Process::pipe(function (Pipe $pipe) {
$pipe->command('cat example.txt');
$pipe->command('grep -i "laravel"');
});
if ($result->successful()) {
// ...
}개별 프로세스 설정이 필요 없다면 명령어 문자열 배열을 바로 전달해도 됩니다.
$result = Process::pipe([
'cat example.txt',
'grep -i "laravel"',
]);파이프라인의 출력도 실시간으로 처리할 수 있습니다.
$result = Process::pipe(function (Pipe $pipe) {
$pipe->command('cat example.txt');
$pipe->command('grep -i "laravel"');
}, function (string $type, string $output) {
echo $output;
});as 메서드로 각 프로세스에 이름을 붙이면 출력 클로저에서 어느 프로세스의 출력인지 구분할 수 있습니다.
$result = Process::pipe(function (Pipe $pipe) {
$pipe->as('first')->command('cat example.txt');
$pipe->as('second')->command('grep -i "laravel"');
}, function (string $type, string $output, string $key) {
// $key로 어느 프로세스의 출력인지 확인
});비동기 프로세스
start 메서드를 사용하면 프로세스를 백그라운드에서 비동기적으로 실행할 수 있습니다. running 메서드로 프로세스가 아직 실행 중인지 확인할 수 있으며, wait로 완료를 기다리고 결과를 가져올 수 있습니다.
$process = Process::timeout(120)->start('bash import.sh');
while ($process->running()) {
// 다른 작업 처리...
}
$result = $process->wait();프로세스 ID와 시그널
id 메서드로 운영체제가 할당한 프로세스 ID를 가져올 수 있습니다.
$process = Process::start('bash import.sh');
return $process->id();signal 메서드로 실행 중인 프로세스에 시그널을 보낼 수 있습니다. 사용 가능한 시그널 상수 목록은 PHP 공식 문서를 참고하세요.
$process->signal(SIGUSR2);비동기 프로세스 출력
비동기 프로세스가 실행 중일 때 output과 errorOutput으로 전체 출력을 가져올 수 있습니다. 마지막으로 읽은 이후에 새로 추가된 출력만 가져오려면 latestOutput과 latestErrorOutput을 사용하세요.
$process = Process::timeout(120)->start('bash import.sh');
while ($process->running()) {
echo $process->latestOutput();
echo $process->latestErrorOutput();
sleep(1);
}start 메서드의 두 번째 인자로 클로저를 전달하면 출력을 실시간으로 처리할 수도 있습니다.
$process = Process::start('bash import.sh', function (string $type, string $output) {
echo $output;
});
$result = $process->wait();프로세스 완료를 기다리는 대신, 특정 출력이 나타날 때까지만 기다리고 싶다면 waitUntil 메서드를 사용하세요. 클로저가 true를 반환하면 대기를 멈춥니다.
$process = Process::start('bash import.sh');
$process->waitUntil(function (string $type, string $output) {
return $output === 'Ready...';
});비동기 프로세스 타임아웃
비동기 프로세스 실행 중에 타임아웃이 발생했는지 확인하려면 ensureNotTimedOut 메서드를 사용하세요. 타임아웃이 발생한 경우 타임아웃 예외가 던져집니다.
$process = Process::timeout(120)->start('bash import.sh');
while ($process->running()) {
$process->ensureNotTimedOut();
// ...
sleep(1);
}동시 프로세스
Laravel은 여러 프로세스를 동시에 실행하는 프로세스 풀도 지원합니다. pool 메서드에 Illuminate\Process\Pool 인스턴스를 받는 클로저를 전달하여 풀을 구성합니다.
use Illuminate\Process\Pool;
use Illuminate\Support\Facades\Process;
$pool = Process::pool(function (Pool $pool) {
$pool->path(__DIR__)->command('bash import-1.sh');
$pool->path(__DIR__)->command('bash import-2.sh');
$pool->path(__DIR__)->command('bash import-3.sh');
})->start(function (string $type, string $output, int $key) {
// 실시간 출력 처리
});
while ($pool->running()->isNotEmpty()) {
// 모든 프로세스가 완료될 때까지 대기
}
$results = $pool->wait();wait 메서드는 배열 형태의 결과를 반환하며, 각 프로세스의 결과를 키로 접근할 수 있습니다.
$results = $pool->wait();
echo $results[0]->output();풀을 시작하고 즉시 결과를 기다리려면 concurrently 메서드를 사용하세요. PHP의 배열 구조 분해와 함께 사용하면 더욱 간결합니다.
[$first, $second, $third] = Process::concurrently(function (Pool $pool) {
$pool->path(__DIR__)->command('ls -la');
$pool->path(app_path())->command('ls -la');
$pool->path(storage_path())->command('ls -la');
});
echo $first->output();풀 프로세스 이름 지정
숫자 키 대신 의미 있는 이름으로 결과를 구분하려면 as 메서드로 각 프로세스에 문자열 키를 지정하세요. 이 키는 start 메서드의 클로저에도 전달됩니다.
$pool = Process::pool(function (Pool $pool) {
$pool->as('first')->command('bash import-1.sh');
$pool->as('second')->command('bash import-2.sh');
$pool->as('third')->command('bash import-3.sh');
})->start(function (string $type, string $output, string $key) {
// $key로 어느 프로세스의 출력인지 확인
});
$results = $pool->wait();
return $results['first']->output();풀 프로세스 ID와 시그널
풀의 running 메서드는 실행 중인 모든 프로세스의 컬렉션을 반환합니다. 이를 통해 각 프로세스의 ID를 쉽게 조회할 수 있습니다.
$processIds = $pool->running()->each->id();풀 내의 모든 프로세스에 시그널을 한 번에 보내려면 풀 객체에 직접 signal 메서드를 호출하세요.
$pool->signal(SIGUSR2);테스트
Laravel의 프로세스 서비스는 테스트 작성을 위한 강력한 기능을 제공합니다. Process 파사드의 fake 메서드를 사용하면 실제 프로세스를 실행하지 않고 가짜 결과를 반환하도록 설정할 수 있습니다.
프로세스 페이킹
다음과 같이 프로세스를 실행하는 라우트가 있다고 가정해보겠습니다.
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Route;
Route::get('/import', function () {
Process::run('bash import.sh');
return 'Import complete!';
});이 라우트를 테스트할 때 Process::fake()를 호출하면 모든 프로세스 실행이 성공한 것처럼 처리됩니다. 이후 어서션으로 특정 프로세스가 실제로 실행 요청을 받았는지도 확인할 수 있습니다.
Pest
<?php
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Process\PendingProcess;
use Illuminate\Support\Facades\Process;
test('process is invoked', function () {
Process::fake();
$response = $this->get('/import');
// 단순 어서션
Process::assertRan('bash import.sh');
// 프로세스 설정까지 검사
Process::assertRan(function (PendingProcess $process, ProcessResult $result) {
return $process->command === 'bash import.sh' &&
$process->timeout === 60;
});
});PHPUnit
<?php
namespace Tests\Feature;
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Process\PendingProcess;
use Illuminate\Support\Facades\Process;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_process_is_invoked(): void
{
Process::fake();
$response = $this->get('/import');
// 단순 어서션
Process::assertRan('bash import.sh');
// 프로세스 설정까지 검사
Process::assertRan(function (PendingProcess $process, ProcessResult $result) {
return $process->command === 'bash import.sh' &&
$process->timeout === 60;
});
}
}fake를 인자 없이 호출하면 모든 프로세스가 출력 없이 성공 처리됩니다. 출력 내용이나 종료 코드를 직접 지정하려면 result 메서드를 사용하세요.
Process::fake([
'*' => Process::result(
output: '테스트 출력',
errorOutput: '테스트 에러 출력',
exitCode: 1,
),
]);특정 프로세스 페이킹
명령어 패턴별로 다른 가짜 결과를 지정할 수 있습니다. *는 와일드카드로 사용할 수 있으며, 페이킹되지 않은 명령어는 실제로 실행됩니다.
Process::fake([
'cat *' => Process::result(
output: '"cat" 명령어 테스트 출력',
),
'ls *' => Process::result(
output: '"ls" 명령어 테스트 출력',
),
]);종료 코드나 에러 출력을 별도로 지정할 필요가 없다면 문자열로 간단히 지정할 수도 있습니다.
Process::fake([
'cat *' => '"cat" 명령어 테스트 출력',
'ls *' => '"ls" 명령어 테스트 출력',
]);프로세스 시퀀스 페이킹
같은 명령어가 여러 번 실행될 때 호출마다 다른 결과를 반환하도록 하려면 sequence 메서드를 사용하세요.
Process::fake([
'ls *' => Process::sequence()
->push(Process::result('첫 번째 실행 결과'))
->push(Process::result('두 번째 실행 결과')),
]);비동기 프로세스 라이프사이클 페이킹
비동기 프로세스를 테스트할 때는 running 메서드가 몇 번 true를 반환해야 하는지, 어떤 출력이 순서대로 나와야 하는지 등을 세밀하게 제어해야 합니다. 다음 라우트를 예로 들겠습니다.
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
Route::get('/import', function () {
$process = Process::start('bash import.sh');
while ($process->running()) {
Log::info($process->latestOutput());
Log::info($process->latestErrorOutput());
}
return 'Done';
});이 코드를 테스트할 때는 describe 메서드로 비동기 프로세스의 라이프사이클을 정의하세요.
Process::fake([
'bash import.sh' => Process::describe()
->output('표준 출력 첫 번째 줄')
->errorOutput('에러 출력 첫 번째 줄')
->output('표준 출력 두 번째 줄')
->exitCode(0)
->iterations(3),
]);output/errorOutput: 순서대로 반환될 출력 줄을 지정합니다.exitCode: 프로세스의 최종 종료 코드를 지정합니다.iterations:running메서드가true를 반환할 횟수를 지정합니다.
사용 가능한 어서션
assertRan
특정 프로세스가 실행되었는지 어서트합니다.
use Illuminate\Support\Facades\Process;
Process::assertRan('ls -la');클로저를 전달하면 프로세스의 설정을 세부적으로 검사할 수 있습니다. 클로저가 true를 반환하면 어서션이 통과합니다. $process는 Illuminate\Process\PendingProcess, $result는 Illuminate\Contracts\Process\ProcessResult 인스턴스입니다.
Process::assertRan(fn ($process, $result) =>
$process->command === 'ls -la' &&
$process->path === __DIR__ &&
$process->timeout === 60
);assertDidntRun
특정 프로세스가 실행되지 않았는지 어서트합니다.
use Illuminate\Support\Facades\Process;
Process::assertDidntRun('ls -la');클로저를 전달할 수도 있으며, 클로저가 true를 반환하면 어서션이 실패합니다.
Process::assertDidntRun(fn (PendingProcess $process, ProcessResult $result) =>
$process->command === 'ls -la'
);assertRanTimes
특정 프로세스가 지정한 횟수만큼 실행되었는지 어서트합니다.
use Illuminate\Support\Facades\Process;
Process::assertRanTimes('ls -la', times: 3);클로저를 사용하면 조건을 추가로 지정할 수 있습니다. 클로저가 true를 반환하고 지정한 횟수만큼 실행된 경우에만 어서션이 통과합니다.
Process::assertRanTimes(function (PendingProcess $process, ProcessResult $result) {
return $process->command === 'ls -la';
}, times: 3);예상치 못한 프로세스 실행 방지
테스트 중에 페이킹되지 않은 프로세스가 실제로 실행되는 것을 막으려면 preventStrayProcesses 메서드를 호출하세요. 이 메서드를 호출한 뒤 페이킹 결과가 정의되지 않은 프로세스가 실행되면 예외가 발생합니다.
use Illuminate\Support\Facades\Process;
Process::preventStrayProcesses();
Process::fake([
'ls *' => '테스트 출력...',
]);
// 페이킹된 결과 반환
Process::run('ls -la');
// 예외 발생!
Process::run('bash import.sh');