Checking how many agents are working

How this works
Contact
← Blog
A cinematic photograph of a steel hand-crank handing a small brass capsule through a slot in a dark panel, an amber light on the far side, in teal and steel, the AMARBARO mark and wordmark centred over it.
✎blog post

Running other programs from Mojo

The short version

mojo-subprocess runs a command, captures its output and stops it on a timeout with the same results as Python's subprocess.run, and mojo-posix covers the lower-level cases.

What this is about

Your program does not have to do everything itself. It can start another program, wait for it, and read what it says. That is how shell scripts work, and it is how a build tool calls a compiler or a backup script calls a copy command.

In Python, subprocess.run does this. In Mojo, our mojo-subprocess library does the same, with the same names and the same results. This article shows how to use it and what happens when something goes wrong.

Why it matters

Many useful scripts are glue. They call git, ffmpeg or ls and decide what to do with the answer. If you can run a command and read the result, you can wire together tools you already have.

The risky part is a command that never ends, or one that prints a huge amount. A careless script hangs forever or uses up memory. A good library handles both. This one reads standard output and error output together, so neither pipe blocks the other.

How to do it, step by step

1. Add the library. Use pixi add mojo-subprocess, with the steps from the mojo-libs page.

2. Run a command and read its output. We ran this on Mojo 1.2.0:

from subprocess import run


def main() raises:
    var r = run(["echo", "hi there"], timeout=5.0)
    print(r.returncode, r.text())
    var s = run(["sort"], input="b\na\n".as_bytes())
    print(s.text())

It printed:

0 hi there

a
b

What happened:

  1. run([...]) takes the command as a list of words. The first word is the program. Words with spaces stay together, so there is no need for shell quoting.
  2. r.returncode is the exit number. Zero means success. A program that dies from a signal gives minus the signal number, such as -9.
  3. r.text() turns the captured standard output into text. r.stdout and r.stderr are the raw bytes.
  4. The second call gives sort some input on its standard input, and reads the sorted answer.

3. Stop a command that takes too long. Pass timeout in seconds. We asked for sleep 5 with a 1 second limit:

var r = run(["sleep", "5"], timeout=1.0)

The program stopped with:

Command 'sleep' timed out after 1.0 seconds

The library sends the kill signal, SIGKILL, and raises an error, as Python does. In a real script you would catch the error and carry on.

4. Make a failure an error. Add check=True, and a non-zero exit becomes an error that says returned non-zero exit status N. Without it, you check returncode yourself.

5. Choose the folder and environment. cwd sets the working folder. env takes a list of NAME=value and replaces the environment. Leave it empty to inherit yours.

What it was checked against

The README compares it with Python's subprocess on exit codes and signal deaths, a flood of 3 MB on standard output and 3 MB on standard error at once, a 5 MB input echo, a child that exits without reading its input, and head closing early. Six of six planted bugs were caught. Error texts for the timeout and a missing program are the library's own, so only the behavior matches, not every word.

Speed

On a Ryzen 7 7800X3D with a load average near 29, run(["true"]) took 418 microseconds and moved 0.60 GB per second through cat. Python took 543 to 1,155 microseconds and 0.35 to 0.47 GB per second across runs. Because the machine was busy, we trust the direction more than the exact numbers.

The lower level: mojo-posix

If run is too simple, mojo-posix gives you the building blocks: spawn to start a child with its own folder, environment and log files, reap to collect its exit code without waiting, and PollSet to wait on signals and sockets together.

It has one sharp edge. If you read signals through signal_fd, you must call block_signals first in main(). The Mojo runtime starts worker threads that catch signals the main thread blocks. Without the call, 14 of 100 child-exit signals were lost in testing. The call re-runs your program once, so code before it runs twice, and it refuses to work under mojo run: build a binary first.

Spawning itself takes about the same time as Python's. 1,000 spawns of /bin/true took 316 to 317 ms in Mojo against 305 to 317 ms in Python, because the kernel does the work in both. Mojo used about 1 MB less memory.

What it needs

Linux and glibc 2.29 or newer. On Linux 5.3 or newer it waits on a process handle. Older kernels fall back to checking the child every millisecond. The program name is searched on your PATH, even if env sets another PATH. Pass a full path in that case.

Both libraries now live in mojo-libs, under libs/posix. The older mojo-subprocess and mojo-posix repositories are read-only.

Words you may not know

  • Exit code: the number a program returns when it stops. Zero means it worked.
  • Standard output and standard error: the two channels a program uses for results and for complaints.
  • Timeout: a time limit after which you stop waiting.
  • Signal: a short message the system sends to a running program, such as "stop now".
  • Pipe: a one-way channel between two programs.

Try it

  1. Run the echo and sort example above.
  2. Add check=True and run a command that fails, such as ls /missing, to see the error.
  3. Read the mojo-subprocess README and its docs/api.md.
  4. Browse mojo-posix when you need to start many children at once.

Comments

No comments yet.

Log in to comment.