nginx worker environment
This project is maintained by wangfakang
nginx 的环境变量的解析
做了个实验发现,再启动nginx时设置的环境变量(在当前的shell环境)然后在子进程中去打印 的时候就不见了。 然后看了下nginx的源码才知道,在启动worker进程的时候,会删除之前的一些环境变量。所以 要在子进程中使用的话则要使用nginx指令env来进行设置。
Syntax: env variable[=value];
Default:
env TZ;
Context: main
如:
env PERL5LIB=/tmp; 注意:等号左右不可以有空格。
进程初始化的时候:
static void
ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker)
{
sigset_t set;
uint64_t cpu_affinity;
ngx_int_t n;
ngx_uint_t i;
struct rlimit rlmt;
ngx_core_conf_t *ccf;
ngx_listening_t *ls;
//配置一些环境变量
if (ngx_set_environment(cycle, NULL) == NULL) {
/* fatal */
exit(2);
}
//获取配置信息
ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);
if (worker >= 0 && ccf->priority != 0) {
if (setpriority(PRIO_PROCESS, 0, ccf->priority) == -1) {
ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
"setpriority(%d) failed", ccf->priority);
}
}
````
}
char **
ngx_set_environment(ngx_cycle_t *cycle, ngx_uint_t *last)
{
char **p, **env;
ngx_str_t *var;
ngx_uint_t i, n;
ngx_core_conf_t *ccf;
ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);
if (last == NULL && ccf->environment) {
return ccf->environment;
}
var = ccf->env.elts;
for (i = 0; i < ccf->env.nelts; i++) {
if (ngx_strcmp(var[i].data, "TZ") == 0
|| ngx_strncmp(var[i].data, "TZ=", 3) == 0)
{
goto tz_found;
}
}
var = ngx_array_push(&ccf->env);
if (var == NULL) {
return NULL;
}
var->len = 2;
var->data = (u_char *) "TZ";
var = ccf->env.elts;
tz_found:
n = 0;
for (i = 0; i < ccf->env.nelts; i++) {
if (var[i].data[var[i].len] == '=') {
n++;
continue;
}
for (p = ngx_os_environ; *p; p++) {
if (ngx_strncmp(*p, var[i].data, var[i].len) == 0
&& (*p)[var[i].len] == '=')
{
n++;
break;
}
}
}
if (last) {
env = ngx_alloc((*last + n + 1) * sizeof(char *), cycle->log);
*last = n;
} else {
env = ngx_palloc(cycle->pool, (n + 1) * sizeof(char *));
}
if (env == NULL) {
return NULL;
}
n = 0;
for (i = 0; i < ccf->env.nelts; i++) {
if (var[i].data[var[i].len] == '=') {
env[n++] = (char *) var[i].data;
continue;
}
for (p = ngx_os_environ; *p; p++) {
if (ngx_strncmp(*p, var[i].data, var[i].len) == 0
&& (*p)[var[i].len] == '=')
{
env[n++] = *p;
break;
}
}
}
env[n] = NULL;
if (last == NULL) {
ccf->environment = env;
environ = env;
}
return env;
}
在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流