Processes
- Introduction
- Running processes
- Process options
- Reading output while a process runs
- Starting processes
- Concurrent processes
- Testing
Introduction
Laravel's laravel::process module provides an expressive API for invoking external processes (such as ffmpeg or git) from your application. It captures stdout, stderr, and exit codes, enforces timeouts, terminates child processes if the calling request is cancelled, and lets you fake external commands in tests so your suite never depends on installed binaries.
Running processes
Use process::run to execute a command and wait for it to finish. Pass arguments as an array so each item is passed directly to the program without invoking a shell:
1use laravel::process;23pub async fn show() -> laravel::Result<String> {4 let result = process::run(["git", "log", "-1", "--format=%h %s"]).await?;56 Ok(result.output().into_owned())7}1use laravel::process;23pub async fn show() -> laravel::Result<String> {4 let result = process::run(["git", "log", "-1", "--format=%h %s"]).await?;56 Ok(result.output().into_owned())7}
Inspect the returned ProcessResult with these methods:
1result.command(); // "git log -1 '--format=%h %s'"2result.successful(); // exited with code 03result.failed(); // exited with another code, or was killed4result.exit_code(); // Some(0), or None when killed5result.output(); // standard output, as text6result.error_output(); // standard error, as text7result.see_in_output("Merge");8result.see_in_error_output("warning");1result.command(); // "git log -1 '--format=%h %s'"2result.successful(); // exited with code 03result.failed(); // exited with another code, or was killed4result.exit_code(); // Some(0), or None when killed5result.output(); // standard output, as text6result.error_output(); // standard error, as text7result.see_in_output("Merge");8result.see_in_error_output("warning");
For programs that output binary data such as images, read raw bytes with output_bytes() and error_output_bytes().
Failed processes
A non-zero exit code returns Ok(result) rather than an error. Some commands use non-zero exit codes during normal operation, such as grep returning 1 when no lines match. When a non-zero exit code should be treated as a failure, chain ensure_successful() to convert it into a ProcessFailed error:
1use laravel::process;23let result = process::run(["git", "pull"]).await?.ensure_successful()?;1use laravel::process;23let result = process::run(["git", "pull"]).await?.ensure_successful()?;
ProcessFailed includes the command, exit code, and trailing output in its message so failures are clear in logs. Returning it from a handler produces a 500 response; inspect it directly with error.is::<ProcessFailed>().
run itself returns an error when the binary cannot be started (such as an io::Error with ErrorKind::NotFound when the program is not installed) or when the process times out (ProcessTimedOut). You can inspect the returned laravel::Error with downcast_ref to handle specific failures:
1use std::io;23use laravel::process::{self, ProcessTimedOut};45match process::run(["ffmpeg", "-i", "clip.mp4", "thumb.jpg"]).await {6 Ok(result) => {7 result.ensure_successful()?;8 }9 Err(error) => {10 if let Some(timed_out) = error.downcast_ref::<ProcessTimedOut>() {11 tracing::warn!(12 output = %timed_out.result().output(),13 "thumbnail generation timed out"14 );1516 return Ok(());17 }1819 if let Some(io) = error.downcast_ref::<io::Error>()20 && io.kind() == io::ErrorKind::NotFound21 {22 tracing::error!("ffmpeg is not installed");2324 return Ok(());25 }2627 return Err(error);28 }29}1use std::io;23use laravel::process::{self, ProcessTimedOut};45match process::run(["ffmpeg", "-i", "clip.mp4", "thumb.jpg"]).await {6 Ok(result) => {7 result.ensure_successful()?;8 }9 Err(error) => {10 if let Some(timed_out) = error.downcast_ref::<ProcessTimedOut>() {11 tracing::warn!(12 output = %timed_out.result().output(),13 "thumbnail generation timed out"14 );1516 return Ok(());17 }1819 if let Some(io) = error.downcast_ref::<io::Error>()20 && io.kind() == io::ErrorKind::NotFound21 {22 tracing::error!("ffmpeg is not installed");2324 return Ok(());25 }2627 return Err(error);28 }29}
Shell commands
When you need shell features such as pipes, redirects, or globs, use Process::shell (sh -c on Unix, cmd /C on Windows):
1use laravel::process::Process;23let result = Process::shell("cat storage/logs/*.log | grep -c ERROR")4 .run()5 .await?;1use laravel::process::Process;23let result = Process::shell("cat storage/logs/*.log | grep -c ERROR")4 .run()5 .await?;
Never interpolate untrusted input into a shell command. Process::shell(format!("convert {name} thumbnail.png")) allows command injection. Pass user input as separate arguments to Process::new instead, where it is never interpreted by a shell.
Process options
Construct a Process builder to customize working directory, timeouts, environment variables, or standard input before calling run:
1use laravel::prelude::*;2use laravel::process::Process;34let result = Process::new(["bash", "import.sh"])5 .path("scripts")6 .timeout(2.minutes())7 .env("IMPORT_PATH", "storage/imports")8 .run()9 .await?;1use laravel::prelude::*;2use laravel::process::Process;34let result = Process::new(["bash", "import.sh"])5 .path("scripts")6 .timeout(2.minutes())7 .env("IMPORT_PATH", "storage/imports")8 .run()9 .await?;
Working directory
By default, processes run in your application's base path. Call path to run the process in a different working directory. For example, passing "frontend" runs the process inside the frontend directory of your application's base path. You may also pass an absolute path to run the process in a directory outside your application:
1use laravel::process::Process;23let result = Process::new(["npm", "run", "build"])4 .path("frontend")5 .run()6 .await?;78let result = Process::new(["git", "status"])9 .path("/tmp/builds")10 .run()11 .await?;1use laravel::process::Process;23let result = Process::new(["npm", "run", "build"])4 .path("frontend")5 .run()6 .await?;78let result = Process::new(["git", "status"])9 .path("/tmp/builds")10 .run()11 .await?;
Timeouts
By default, Laravel terminates processes after 60 seconds and returns ProcessTimedOut. Adjust this limit with timeout, disable it with forever(), or set idle_timeout to stop a process that produces no output for a given duration:
1use laravel::prelude::*;2use laravel::process::Process;34Process::new(["bash", "import.sh"])5 .timeout(10.minutes())6 .idle_timeout(30.seconds())7 .run()8 .await?;1use laravel::prelude::*;2use laravel::process::Process;34Process::new(["bash", "import.sh"])5 .timeout(10.minutes())6 .idle_timeout(30.seconds())7 .run()8 .await?;
On ProcessTimedOut, error.result() exposes the output captured before termination and error.is_idle() tells you whether the idle timeout triggered.
Environment variables
Processes inherit your application's environment, including variables loaded from .env. Use env or envs to set variables, and remove_env to strip an inherited variable from the child process. Any variable passed to env or envs overwrites an existing or inherited variable with the same name:
1use laravel::process::Process;23Process::new(["bash", "import.sh"])4 .env("IMPORT_PATH", "storage/imports")5 .envs([("BATCH_SIZE", "500"), ("DRY_RUN", "1")])6 .remove_env("AWS_SECRET_ACCESS_KEY")7 .run()8 .await?;1use laravel::process::Process;23Process::new(["bash", "import.sh"])4 .env("IMPORT_PATH", "storage/imports")5 .envs([("BATCH_SIZE", "500"), ("DRY_RUN", "1")])6 .remove_env("AWS_SECRET_ACCESS_KEY")7 .run()8 .await?;
When invoking untrusted programs, prevent secrets like APP_KEY from leaking by calling without_inheriting_env() and passing only the variables the program needs (typically including PATH):
1Process::new(["node", "render.js"])2 .without_inheriting_env()3 .env("NODE_ENV", "production")4 .env("PATH", "/usr/local/bin:/usr/bin:/bin")5 .run()6 .await?;1Process::new(["node", "render.js"])2 .without_inheriting_env()3 .env("NODE_ENV", "production")4 .env("PATH", "/usr/local/bin:/usr/bin:/bin")5 .run()6 .await?;
Input
Pass standard input to a process with input, which writes the bytes and closes stdin. Without input, stdin is immediately closed so programs never hang waiting for input:
1use laravel::process::Process;23let result = Process::new(["wc", "-l"])4 .input("Taylor\nAbigail\n")5 .run()6 .await?;1use laravel::process::Process;23let result = Process::new(["wc", "-l"])4 .input("Taylor\nAbigail\n")5 .run()6 .await?;
Reading output while a process runs
For long-running builds or imports (such as inside a console command), pass a callback to on_output to receive stdout and stderr chunks as they arrive:
1use laravel::process::{OutputKind, Process};23Process::new(["npm", "run", "build"])4 .on_output(|output| match output.kind() {5 OutputKind::Stdout => print!("{}", output.text()),6 OutputKind::Stderr => eprint!("{}", output.text()),7 })8 .run()9 .await?;1use laravel::process::{OutputKind, Process};23Process::new(["npm", "run", "build"])4 .on_output(|output| match output.kind() {5 OutputKind::Stdout => print!("{}", output.text()),6 OutputKind::Stderr => eprint!("{}", output.text()),7 })8 .run()9 .await?;
Each chunk contains whatever bytes the OS delivered at once and may span partial or multiple lines; buffer and split on newlines yourself if you need line-by-line processing.
If a process writes large volumes of output that you do not want buffered in memory, chain .quietly(). on_output still receives every chunk while the final ProcessResult omits buffered output:
1use laravel::process::Process;23Process::new(["pg_dump", "production"])4 .quietly()5 .on_output(|output| print!("{}", output.text()))6 .run()7 .await?8 .ensure_successful()?;1use laravel::process::Process;23Process::new(["pg_dump", "production"])4 .quietly()5 .on_output(|output| print!("{}", output.text()))6 .run()7 .await?8 .ensure_successful()?;
Starting processes
To launch a process asynchronously while performing other work, call start() to obtain a RunningProcess handle, then await wait() when you need its ProcessResult:
1use laravel::process::Process;23let import = Process::new(["bash", "import.sh"]).forever().start()?;45// Perform other work while the import runs...67let result = import.wait().await?.ensure_successful()?;1use laravel::process::Process;23let import = Process::new(["bash", "import.sh"]).forever().start()?;45// Perform other work while the import runs...67let result = import.wait().await?.ensure_successful()?;
Call id() to inspect the OS process ID and running() to check whether the process is still active.
Reading output as it arrives
Call chunks() on a RunningProcess to consume its output as an async stream so you can await operations on each chunk as it arrives:
1use laravel::process::Process;2use laravel::stream::StreamExt;34let mut import = Process::new(["bash", "import.sh"]).forever().start()?;5let mut chunks = import.chunks();67while let Some(output) = chunks.next().await {8 // Handle output.text() or output.bytes()...9}1011let result = import.wait().await?;1use laravel::process::Process;2use laravel::stream::StreamExt;34let mut import = Process::new(["bash", "import.sh"]).forever().start()?;5let mut chunks = import.chunks();67while let Some(output) = chunks.next().await {8 // Handle output.text() or output.bytes()...9}1011let result = import.wait().await?;
chunks() may only be called once per process. To react to cancellation or other events while streaming, poll the stream inside task::select!.
Waiting for output
For background daemons or servers that keep running after startup, use wait_until to read output chunks until a predicate matches. It returns true when matched, or false if the process exited first:
1use laravel::process::Process;23let mut server = Process::new(["node", "bootstrap/ssr/app.js"])4 .forever()5 .start()?;67if !server8 .wait_until(|output| output.text().contains("Listening"))9 .await10{11 server.wait().await?.ensure_successful()?;12}1use laravel::process::Process;23let mut server = Process::new(["node", "bootstrap/ssr/app.js"])4 .forever()5 .start()?;67if !server8 .wait_until(|output| output.text().contains("Listening"))9 .await10{11 server.wait().await?.ensure_successful()?;12}
Keep the match pattern short, since longer strings may be split across two output chunks.
Signals and stopping
Stop a running process gracefully with stop(grace_period). On Unix, Laravel sends Signal::Terminate and force-kills the process if it has not exited when the grace period elapses; on Windows, it terminates the process immediately. Like wait, stop returns a ProcessResult:
1use laravel::prelude::*;2use laravel::process::Process;34let server = Process::new(["node", "bootstrap/ssr/app.js"])5 .forever()6 .start()?;78// ...910let result = server.stop(10.seconds()).await?;1use laravel::prelude::*;2use laravel::process::Process;34let server = Process::new(["node", "bootstrap/ssr/app.js"])5 .forever()6 .start()?;78// ...910let result = server.stop(10.seconds()).await?;
On Unix, send any Signal with signal:
1use laravel::console::Signal;23server.signal(Signal::User2)?;1use laravel::console::Signal;23server.signal(Signal::User2)?;
Dropping a RunningProcess or cancelling an in-flight run, wait, or stop future (for example, when an HTTP client disconnects) automatically terminates the child process and, on Unix, its spawned process group.
Concurrent processes
Run multiple processes concurrently with task::try_join!. If any process fails to start or times out, try_join! returns that error and terminates the others:
1use laravel::process;2use laravel::task;34let (users, posts) = task::try_join!(5 process::run(["bash", "import-users.sh"]),6 process::run(["bash", "import-posts.sh"]),7)?;89println!("{}", users.output());1use laravel::process;2use laravel::task;34let (users, posts) = task::try_join!(5 process::run(["bash", "import-users.sh"]),6 process::run(["bash", "import-posts.sh"]),7)?;89println!("{}", users.output());
Testing
Call process::fake() in your tests to record external commands without executing them. By default, every faked process succeeds with empty output:
1use laravel::process;2use laravel::testing::prelude::*;34#[laravel::test]5async fn importing_runs_the_script(app: Application) {6 let processes = process::fake();78 app.post("/imports").await.assert_ok();910 processes.assert_ran("bash import.sh");11}1use laravel::process;2use laravel::testing::prelude::*;34#[laravel::test]5async fn importing_runs_the_script(app: Application) {6 let processes = process::fake();78 app.post("/imports").await.assert_ok();910 processes.assert_ran("bash import.sh");11}
Keep the returned fake handle alive while exercising your application; dropping it restores real process execution.
Faking results
Use .with(pattern, result) to fake commands matching a wildcard pattern (* matches any text) in registration order. Pass a string, a process::result(), a process::sequence, or a closure receiving &Invocation:
1use laravel::process::{self, Invocation};23let processes = process::fake()4 .with("git rev-parse *", "a1b2c3\n")5 .with(6 "bash import.sh",7 process::result()8 .output("Importing...\n")9 .error_output("No such file\n")10 .exit_code(1),11 )12 .with("ls *", process::sequence(["first\n", "second\n"]))13 .with("wc -l", |process: &Invocation| {14 let lines = process15 .input()16 .unwrap_or_default()17 .iter()18 .filter(|byte| **byte == b'\n')19 .count();2021 process::result().output(format!("{lines}\n"))22 });1use laravel::process::{self, Invocation};23let processes = process::fake()4 .with("git rev-parse *", "a1b2c3\n")5 .with(6 "bash import.sh",7 process::result()8 .output("Importing...\n")9 .error_output("No such file\n")10 .exit_code(1),11 )12 .with("ls *", process::sequence(["first\n", "second\n"]))13 .with("wc -l", |process: &Invocation| {14 let lines = process15 .input()16 .unwrap_or_default()17 .iter()18 .filter(|byte| **byte == b'\n')19 .count();2021 process::result().output(format!("{lines}\n"))22 });
Once a process::sequence runs out of results, any additional matching command returns an error. When your code streams output with on_output or chunks, Laravel delivers faked output one line at a time.
Faking failures
Simulate timeouts with timed_out(), which fails with ProcessTimedOut, or startup failures with failed_to_start(kind), which fails with an io::Error:
1use std::io;23use laravel::process;45let processes = process::fake()6 .with("ffmpeg *", process::result().output("frame=120\n").timed_out())7 .with(8 "convert *",9 process::result().failed_to_start(io::ErrorKind::NotFound),10 )11 .with(12 "rsync *",13 process::sequence([process::result().timed_out(), process::result()]),14 );1use std::io;23use laravel::process;45let processes = process::fake()6 .with("ffmpeg *", process::result().output("frame=120\n").timed_out())7 .with(8 "convert *",9 process::result().failed_to_start(io::ErrorKind::NotFound),10 )11 .with(12 "rsync *",13 process::sequence([process::result().timed_out(), process::result()]),14 );
Pairing a failure with a success in process::sequence lets you test retry logic.
Preventing stray processes
Call prevent_stray_processes to fail any command that does not match an explicit .with(..) pattern:
1use laravel::process;23let processes = process::fake()4 .with("git *", "")5 .prevent_stray_processes();1use laravel::process;23let processes = process::fake()4 .with("git *", "")5 .prevent_stray_processes();
Available assertions
While a process fake is active, Laravel records every command your application invokes so you can verify which processes ran, how many times they ran, and in what order. You can chain assertions directly on the handle returned by process::fake(), passing either a command pattern or a closure for custom checks:
1use laravel::prelude::*;2use laravel::process;34let processes = process::fake();56// Exercise your application...78processes9 .assert_ran("git pull")10 .assert_ran_times("git pull", 1)11 .assert_not_ran("git push")12 .assert_ran_in_order(["git pull", "bash import.sh"])13 .assert_ran_where(|process| {14 process.command() == "bash import.sh"15 && process.timeout() == Some(5.minutes().into())16 });1718processes.assert_nothing_ran();1use laravel::prelude::*;2use laravel::process;34let processes = process::fake();56// Exercise your application...78processes9 .assert_ran("git pull")10 .assert_ran_times("git pull", 1)11 .assert_not_ran("git push")12 .assert_ran_in_order(["git pull", "bash import.sh"])13 .assert_ran_where(|process| {14 process.command() == "bash import.sh"15 && process.timeout() == Some(5.minutes().into())16 });1718processes.assert_nothing_ran();
Invocation exposes command, program, arguments, path, timeout, env, and input. Because command strings quote arguments containing spaces, such as convert 'my photo.png' thumbnail.png, compare program() and arguments() directly when checking exact argument lists:
1processes.assert_ran_where(|process| {2 process.program() == "convert"3 && process.arguments() == ["my photo.png", "thumbnail.png"]4});1processes.assert_ran_where(|process| {2 process.program() == "convert"3 && process.arguments() == ["my photo.png", "thumbnail.png"]4});