The basic idea behind the Environment module is to load configuration values (i.e. values that a program needs at run-time) from a shell script which exports some variables in a given namespace (let's say PFX_
).
We let the shell act in the background - using just some env(1)
and pipe(2)
tricks to redirect and capture the variables - which in turn gives us a great deal of power and flexibility in just a couple of C lines.
The following is a very simple configuration file in which three variables are set and export'ed
to the environment:
SET_PFX_VAR1="" [ ! -z "$SET_PFX_VAR1" ] && export PFX_VAR1="tip" export PFX_VAR2="tap" export PFX_VAR3=$((10 * 100 * 1000))
Things worth noting are:
PFX_VAR3
;cat /proc/something
) is available;source
(aka "."
) shell builtin(1).The C code needed to access the former configuration file is:
size_t i; const char *v, *vp[] = { "PFX_VAR1", "PFX_VAR2", "PFX_VAR3" }; // load, parse, eval, etc. variables with PFX_ prefix from my.conf // into the process environment dbg_err_if (u_env_init("PFX_", "./my.conf")); // access PFX_VAR{1,2,3} variables and print their values for (i = 0; i < 3; ++i) { v = u_env_var(vp[i]); con("%s = %s", vp[i], v ? v : "UNSET"); }
Functions | |
int | u_env_init (const char *prefix, const char *cfile) |
Load configuration environment. | |
const char * | u_env_var (const char *name) |
Get a configuration variable value. |
int u_env_init | ( | const char * | prefix, | |
const char * | cfile | |||
) |
prefix | variables namespace | |
cfile | configuration file |
Load all configuration variables in the given prefix
namespace from the configuration file cfile
into the environment of the calling process. Complex parameter substitution, conditional evaluations, arithmetics, etc. is done by the shell: the caller has a simple name=value view of the configuration file.
0 | on success | |
~0 | on failure |
Definition at line 87 of file env.c.
References u_snprintf().