What You’ll Learn
- Starting a background process with
sbx.commands.run(cmd, background=True)
- Inspecting the returned
CommandHandle and its pid
- Listing all running processes with
sbx.commands.list()
- Killing a process by PID with
sbx.commands.kill(pid)
- Verifying the process was removed by listing again
- Proper cleanup with
try/finally and sbx.kill()
Prerequisites
This example is available in Python. TypeScript version coming soon.
Code Walkthrough
Start a command in the background by passing background=True. The call returns immediately with a CommandHandle containing the process PID:
from declaw import Sandbox
sbx = Sandbox.create(template="base", timeout=300)
try:
handle = sbx.commands.run("sleep 30 && echo done", background=True)
print(f"Background process started with pid: {handle.pid}")
List all running processes — each entry has a pid and cmd:
processes = sbx.commands.list()
for proc in processes:
print(f" pid={proc.pid} cmd={proc.cmd!r}")
Kill the background process by PID:
killed = sbx.commands.kill(handle.pid)
print(f"kill({handle.pid}) returned: {killed}")
List again to confirm the process is gone:
processes = sbx.commands.list()
if not processes:
print(" No running processes (as expected).")
else:
for proc in processes:
print(f" pid={proc.pid} cmd={proc.cmd!r}")
finally:
sbx.kill()
print("Sandbox killed.")
Expected Output
==================================================
Declaw Background Process Example
==================================================
--- Creating Sandbox ---
Sandbox created: sbx_abc123
--- Starting Background Process ---
Background process started with pid: 42
--- Listing Processes ---
pid=42 cmd='sleep 30 && echo done'
--- Killing Process ---
kill(42) returned: True
--- Listing Processes After Kill ---
No running processes (as expected).
--- Cleaning Up ---
Sandbox killed.
==================================================
Done!
==================================================