2016-08-02

C: Linux sysinfo loads interpretation

There's this handy syscall in Linux, the sysinfo (kernel source), which returns some metrics about the current process.

What immediately stands out, is the load averages array. They are long values, how to make them to be our beloved fractional numbers?

These three values are scaled up by 65536, or more precisely by SI_LOAD_SHIFT. So we just divide them:

#include <sys/sysinfo.h>

// ...

struct sysinfo memInfo;
sysinfo(&memInfo);
printf("sysinfo: load1 = %2.2f\n", (float)memInfo.loads[0] / (float)(1 << SI_LOAD_SHIFT) );

2016-08-01

C: How to Detect LD_PRELOAD

As I'm writing a lib to be preloaded under something heavy, I tried to detect if LD_PRELOAD is set or not. For fun.

The easiest way to check is...get the environment variable! It is so straightforward, that I feel the urge to write it down :-)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 char *env_val = getenv("LD_PRELOAD");
 if (env_val[0] != 0) // May be set but value is empty.
  printf("LD_PRELOAD active: \"%s\"\n", env_val);
 return 0;
}

Note, this only checks the existence of the variable, not that if it is actually loaded...