Skip to content

Instantly share code, notes, and snippets.

@squeed
Last active November 7, 2023 09:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squeed/0d70706b1e52a31fa3d756b4ae42b825 to your computer and use it in GitHub Desktop.
Save squeed/0d70706b1e52a31fa3d756b4ae42b825 to your computer and use it in GitHub Desktop.
How to override _SC_NPROCESSORS_CONF when you know what you're doing.
// SPDX-License-Identifier: Apache-2.0
//
// Override sysconf CPU count detection. Why? Because cgroups exist. A process
// running on a 256-core machine, but with 2 cores of CPU granted, should not start
// 256 worker threads. I'm looking at you, gRPC.
//
// If you wanted, you could parse the cgroup knobs automatically.
//
// compile with
// gcc -shared -fPIC -Wall -Wextra -Werror numcpu_override.c -o numcpu_override.so -ldl
//
// run with
// LD_PRELOAD=$PWD/numcpu_override.so NUMCPUS=2 ./sysconf
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef long (*orig_sysconf_f_type)(int name);
long numcpus = 0;
long sysconf(int name) {
orig_sysconf_f_type orig;
orig = (orig_sysconf_f_type)dlsym(RTLD_NEXT, "sysconf");
if (name != _SC_NPROCESSORS_CONF && name != _SC_NPROCESSORS_ONLN) {
return orig(name);
}
if (numcpus > 0) {
return numcpus;
}
char *env = getenv("NUMCPUS");
if (env == NULL || strlen(env) == 0) {
return orig(name);
}
numcpus = strtol(env, NULL, 10);
if (errno != 0 || numcpus < 1) {
return orig(name);
}
return numcpus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment