logo
0
0
WeChat Login
feat: add Zig implementation of mini

Minimal Init (MINI) for container - Zig Implementation

Zig reimplementation of mini.c, with identical functionality.

Files

  • mini.zig: The Zig implementation
  • mini: The compiled executable

Implementation Details

Zig API Mapping

C APIZig API
fork()std.posix.fork()
execl()std.posix.execveZ()
stat()std.posix.fstatatZ()
waitpid()std.posix.waitpid()
sigtimedwait()extern "c" binding to libc
sigdelset()extern "c" binding to libc
sigprocmask()std.posix.sigprocmask()
opendir()/readdir()/closedir()extern "c" bindings to libc
getenv()std.posix.getenvZ()
nanosleep()std.time.sleep()

Executable Detection

The isExecutable() function checks if a file is executable by:

  1. Using posix.fstatatZ() to get file stat info
  2. Verifying it's a regular file (linux.S.IFREG)
  3. Checking if it has user execute permission (linux.S.IXUSR)

Process Execution

For each executable file found, the program:

  1. Uses posix.fork() to create a child process
  2. In the child process, uses posix.execveZ() to replace the process with the executable file
  3. In the parent process, enters a sigtimedwait() signal loop to handle child events

Loop Mode

When argv[0] ends with "loop", the program enters loop mode:

  • Scans LOOP_DIR (default /.loop.d/) instead of MINI_DIR
  • Tracks all spawned child processes (pid -> path mapping)
  • When a child process exits, restarts it after LOOP_INTERVAL ms (default 2000ms)

Signal Handling

The program blocks all signals except crash signals (SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGABRT, SIGTRAP, SIGSYS, SIGTTIN, SIGTTOU), then uses sigtimedwait() to handle:

  • SIGINT / SIGTERM: graceful exit
  • SIGCHLD: reap children, restart in loop mode

Environment Variables

VariableDescriptionDefault
MINI_DIRDirectory to scan for executables (normal mode)/.mini.d
LOOP_DIRDirectory to scan for executables (loop mode)/.loop.d
LOOP_INTERVALRestart delay in ms (loop mode)2000
MINI_VERBOSEEnable verbose output (1 or true)off

Compilation

# Dynamic linking (glibc) zig build-exe mini.zig -O ReleaseSmall -lc # Static linking (musl, for containers) zig build-exe mini.zig -O ReleaseSmall -target x86_64-linux-musl -lc

Usage

# Normal mode (scans /.mini.d/) ./mini # Verbose mode ./mini verbose # or MINI_VERBOSE=1 ./mini # Custom scan directory MINI_DIR=./scripts ./mini # Loop mode (symlink or rename executable to end with "loop") ln -s mini mini-loop ./mini-loop