Skip to content

Instantly share code, notes, and snippets.

@ab
Last active June 6, 2025 19:52
Show Gist options
  • Save ab/f8e42d7e110e2b40caca9f79a6ec1815 to your computer and use it in GitHub Desktop.
Save ab/f8e42d7e110e2b40caca9f79a6ec1815 to your computer and use it in GitHub Desktop.
Benchmark OS fork/exec/posix_spawn
#include <unistd.h>
#include <err.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <ctype.h>
#include <spawn.h>
extern char **environ;
void parent_waitpid(pid_t pid) {
int status;
if (waitpid(pid, &status, 0) != pid) {
err(EXIT_FAILURE, "waitpid()");
}
if (status != 0) {
errx(EXIT_FAILURE, "status code is non-zero");
}
}
// test posix_spawn() performance
void posix_spawn_test(char *cmd) {
pid_t pid;
char * const argv[] = { cmd, NULL };
if (posix_spawn(&pid, cmd, NULL, NULL, argv, environ) != 0) {
err(EXIT_FAILURE, "posix_spawn()");
}
parent_waitpid(pid);
}
int main(int argc, char** argv) {
int count = 10000;
char *command = "/usr/bin/true";
// usage: ./bench COUNT [COMMAND]
if (argc == 3) {
count = atoi(argv[1]);
command = argv[2];
} else if (argc == 2) {
count = atoi(argv[1]);
} else {
errx(1, "usage: %s COUNT [COMMAND]", argv[0]);
}
printf("Spawning %d iterations of %s\n", count, command);
for (int i = 0; i < count; i++) {
posix_spawn_test(command);
}
}
[tasks.build]
description = "Compile"
run = "gcc -o bench bench.c"
#!/bin/bash
count="${1-1000}"
cmd="${2-/usr/bin/true}"
echo "Testing $count iterations of $cmd"
for (( i=0; i < count; i++ )); do
"$cmd"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment