Skip to main content
Represents a background process started with startProcess(), providing methods to monitor, control, and interact with the process.

Type Definition

interface Process {
  readonly id: string;
  readonly pid?: number;
  readonly command: string;
  readonly status: ProcessStatus;
  readonly startTime: Date;
  readonly endTime?: Date;
  readonly exitCode?: number;
  readonly sessionId?: string;
  
  kill(signal?: string): Promise<void>;
  getStatus(): Promise<ProcessStatus>;
  getLogs(): Promise<{ stdout: string; stderr: string }>;
  waitForLog(pattern: string | RegExp, timeout?: number): Promise<WaitForLogResult>;
  waitForPort(port: number, options?: WaitForPortOptions): Promise<void>;
  waitForExit(timeout?: number): Promise<WaitForExitResult>;
}

type ProcessStatus =
  | 'starting'
  | 'running'
  | 'completed'
  | 'failed'
  | 'killed'
  | 'error';

Properties

id
string
required
Unique process identifier
pid
number
System process ID (if available and running)
command
string
required
Command that was executed
status
ProcessStatus
required
Current process status:
  • starting - Process is being initialized
  • running - Process is actively running
  • completed - Process exited successfully (code 0)
  • failed - Process exited with non-zero code
  • killed - Process was terminated by signal
  • error - Process failed to start
startTime
Date
required
When the process was started
endTime
Date
When the process ended (if completed)
exitCode
number
Process exit code (if completed)
sessionId
string
Session ID if the process was started in a specific session

Methods

kill()

Terminate the process.
await process.kill(); // SIGTERM (default)
await process.kill('SIGKILL'); // Force kill

getStatus()

Get current process status (refreshed from container).
const status = await process.getStatus();
console.log('Process status:', status);

getLogs()

Get accumulated logs since process started.
const { stdout, stderr } = await process.getLogs();
console.log('Output:', stdout);
console.error('Errors:', stderr);

waitForLog()

Wait for a log pattern to appear in process output.
const result = await process.waitForLog('Server started', 30000);
console.log('Found:', result.line);

// With regex
const result = await process.waitForLog(/Port: (\d+)/);
console.log('Port:', result.match[1]);

waitForPort()

Wait for a port to become ready.
await process.waitForPort(3000); // HTTP check
await process.waitForPort(5432, { mode: 'tcp' }); // TCP check
await process.waitForPort(8080, {
  path: '/health',
  status: 200,
  timeout: 30000
});

waitForExit()

Wait for the process to exit.
const { exitCode } = await process.waitForExit();
console.log('Process exited with code:', exitCode);

// With timeout
try {
  await process.waitForExit(10000);
} catch (error) {
  console.error('Process did not exit within 10 seconds');
}

Example Usage

import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.SANDBOX, 'my-sandbox');

// Start a web server
const process = await sandbox.startProcess('npm run dev');

console.log('Process ID:', process.id);
console.log('PID:', process.pid);
console.log('Status:', process.status);

// Wait for server to be ready
await process.waitForLog('Server listening');
await process.waitForPort(3000);

console.log('Server is ready');

// Monitor the process
setInterval(async () => {
  const status = await process.getStatus();
  if (status !== 'running') {
    console.error('Server stopped');
  }
}, 5000);

Example: Training Job

const process = await sandbox.startProcess('python train.py');

// Monitor progress
let lastEpoch = 0;
while (true) {
  const result = await process.waitForLog(
    /Epoch (\d+) complete/,
    60000
  );
  
  const epoch = parseInt(result.match[1]);
  console.log(`Completed epoch ${epoch}`);
  
  if (epoch >= 100) break;
}

// Wait for completion
const { exitCode } = await process.waitForExit();

if (exitCode === 0) {
  console.log('Training completed successfully');
} else {
  const { stderr } = await process.getLogs();
  console.error('Training failed:', stderr);
}

Example: Health Check Pattern

const process = await sandbox.startProcess('./server');

try {
  // Wait for server to be healthy
  await process.waitForPort(8080, {
    path: '/health',
    timeout: 30000
  });
  
  console.log('Server is healthy');
} catch (error) {
  // Check if process crashed
  const status = await process.getStatus();
  if (status === 'failed' || status === 'error') {
    const { stderr } = await process.getLogs();
    console.error('Server failed to start:', stderr);
  } else {
    console.error('Server health check timeout');
  }
  
  await process.kill();
}

Notes

  • Process objects are returned by startProcess()
  • All methods are async and return Promises
  • Process status is cached - use getStatus() to refresh
  • Logs are accumulated from process start
  • Use waitFor* methods to synchronize with process milestones
  • Processes can outlive the Worker request that created them
  • Processes are automatically cleaned up when sandbox is destroyed

See Also

Build docs developers (and LLMs) love