Skip to content

Instantly share code, notes, and snippets.

@aphor
Forked from thomasdarimont/ReportCpuCount.java
Created November 8, 2018 20:37
Show Gist options
  • Save aphor/cc804f92e20f74f721ae111816ce64b8 to your computer and use it in GitHub Desktop.
Save aphor/cc804f92e20f74f721ae111816ce64b8 to your computer and use it in GitHub Desktop.
Using LD_PRELOAD to pass a fake CPU count to Java on Linux

Build shared library

gcc -shared -fPIC fake-cpu-count.c -o fake-cpu-count.so -ldl

Compile ReportCpuCount

javac ReportCpuCount.java

Run normally

java -cp . ReportCpuCount
#Found 8 CPUs
#...

Run with fake-cpu-count library

LD_PRELOAD=./fake-cpu-count.so java -cp . ReportCpuCount
#Found 2 CPUs
#...
#define _GNU_SOURCE
#include "stdlib.h"
#include <unistd.h>
#include <dlfcn.h>
typedef long int (*orig_sysconf_f_type)(int __name);
long sysconf(int name){
orig_sysconf_f_type orig_sysconf;
orig_sysconf = (orig_sysconf_f_type)dlsym(RTLD_NEXT,"sysconf");
if (name == _SC_NPROCESSORS_CONF){
return 2;
}
return orig_sysconf(name);
}
public class ReportCpuCount {
public static void main(String[] args) throws Exception{
while(true){
System.out.printf("#Found %d CPUs%n", Runtime.getRuntime().availableProcessors());
Thread.sleep(1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment