nginx学习—设置进程title(setproctitle)
刚好看到nginx设置进程title的源码,因此做一些总结。
linux进程实际是以argv[0]处的值来作为进程的title的,因此若需要修改进程的title只需要修改argv[0]处的值即可。
简单的方法就是直接将想要设置的title复制给argv[0]即可,如下示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern char** environ;
int main(int argc, char* argv[])
{
char s_title[] = "xiejian title for simple way!";
size_t i_size = strlen(s_title);
memcpy(argv[0], s_title, i_size);
argv[0][i_size] = '\0';
while(1){
system("ps -ef|awk '$8 ~ /xiejian/ {print $0}'");
sleep(10);
}
}
运行结果为:
但是这种方式是以破坏性的方式,进程的进程title的修改。由于程序的参数存储空间的后面紧跟的就是环境变量的存储位置,在不考虑参数的破坏性的情况下。
命令行参数argv和环境变量信息environ是在一块连续的内存中表示的,并且environ紧跟在argv后面。如下图:
由上图可知过长的title也会损坏环境变量environ的值。因此在nginx中,是将环境变量进行移位存储处理的。下面是nginx处理进程设置title的思路。
/*
* To change the process title in Linux and Solaris we have to set argv[1]
* to NULL and to copy the title to the same place where the argv[0] points to.
* However, argv[0] may be too small to hold a new title. Fortunately, Linux
* and