前几天网上搜索如何更改执行进程的进程名称,并没有得到一个好的答案.
刚刚阅读nginx的源码,发现这样一种解决方案,记录之:
网上说的比较多的是直接更改argv[0],但是如上图中所示,nginx中指出,将argv[1]置为NULL才行,要注意,系统给argv[0]提供的空间可能不足以存储你所要求的新title,解决方案是重新给环境变量申请内存区域,然后将环境变量复制过去(environ是全局变量),参数argv和环境变量在连续的存储空间
这里将argv[1]置为NULL,要注意的是,有这一步,以后想通过argv[]引用参数应该是不可能的了,需要在此之前做好参数的复制存储,不能仅仅是复制参数的指针给另一个变量.
之后原本argv参数和environ所使用的区域都可以被你填充新的进程名字(记得null-terminal)
nginx实现:
- extern char **environ;
-
- static char *ngx_os_argv_last;
-
- ngx_int_t
- ngx_init_setproctitle(ngx_log_t *log)
- {
- u_char *p;
- size_t size;
- ngx_uint_t i;
-
- size = 0;
-
- for (i = 0; environ[i]; i ) {
- size = ngx_strlen(environ[i]) 1;
- }
-
- p = ngx_alloc(size, log);
- if (p == NULL) {
- return NGX_ERROR;
- }
-
- ngx_os_argv_last = ngx_os_argv[0];
-
- for (i = 0; ngx_os_argv[i]; i ) {
- if (ngx_os_argv_last == ngx_os_argv[i]) {
- ngx_os_argv_last = ngx_os_argv[i] ngx_strlen(ngx_os_argv[i]) 1;
- }
- }
-
- for (i = 0; environ[i]; i ) {
- if (ngx_os_argv_last == environ[i]) {
-
- size = ngx_strlen(environ[i]) 1;
- ngx_os_argv_last = environ[i] size;
-
- ngx_cpystrn(p, (u_char *) environ[i], size);
- environ[i] = (char *) p;
- p = size;
- }
- }
-
- ngx_os_argv_last--;
-
- return NGX_OK;
- }
-
-
- void
- ngx_setproctitle(char *title)
- {
- u_char *p;
-
- #if (NGX_SOLARIS)
-
- ngx_int_t i;
- size_t size;
-
- #endif
-
- ngx_os_argv[1] = NULL;
-
- p = ngx_cpystrn((u_char *) ngx_os_argv[0], (u_char *) "nginx: ",
- ngx_os_argv_last - ngx_os_argv[0]);
-
- p = ngx_cpystrn(p, (u_char *) title, ngx_os_argv_last - (char *) p);
-
- #if (NGX_SOLARIS)
-
- size = 0;
-
- for (i = 0; i < ngx_argc; i ) {
- size = ngx_strlen(ngx_argv[i]) 1;
- }
- if (size > (size_t) ((char *) p - ngx_os_argv[0])) {
-
-
-
-
-
-
- p = ngx_cpystrn(p, (u_char *) " (", ngx_os_argv_last - (char *) p);
-
- for (i = 0; i < ngx_argc; i ) {
- p = ngx_cpystrn(p, (u_char *) ngx_argv[i],
- ngx_os_argv_last - (char *) p);
- p = ngx_cpystrn(p, (u_char *) " ", ngx_os_argv_last - (char *) p);
- }
-
- if (*(p - 1) == '' '') {
- *(p - 1) = '')'';
- }
- }
-
- #endif
-
- if (ngx_os_argv_last - (char *) p) {
- ngx_memset(p, NGX_SETPROCTITLE_PAD, ngx_os_argv_last - (char *) p);
- }
-
- ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
- "setproctitle: "%s"", ngx_os_argv[0]);
- }
-
-
|