proc_title.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <mem_check.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20. #include <sys/prctl.h>
  21. #ifndef PR_SET_NAME
  22. #define PR_SET_NAME 15
  23. #endif
  24. #ifndef PR_GET_NAME
  25. #define PR_GET_NAME 16
  26. #endif
  27. static char *arg_start;
  28. static char *arg_end;
  29. static char *env_start;
  30. extern char **environ;
  31. //初始化进程名
  32. void init_proc_title(int argc, char **argv)
  33. {
  34. int i;
  35. arg_start = argv[0]; //程序地址
  36. arg_end = argv[argc - 1] + strlen(argv[argc - 1]) + 1;
  37. env_start = environ[0];
  38. for (i = 0; i < argc; ++i)
  39. argv[i] = STRDUP(argv[i]); //使可以操作argv空间
  40. }
  41. void set_proc_title(const char *title)
  42. {
  43. if(title == NULL)
  44. return ;
  45. int tlen = strlen(title) + 1;
  46. int i;
  47. char *p;
  48. if (arg_start == NULL)
  49. return;
  50. if (arg_end - arg_start < tlen && env_start == arg_end)
  51. {
  52. char *env_end = env_start;
  53. for (i = 0; environ[i]; i++)
  54. {
  55. if (env_end == environ[i])
  56. {
  57. env_end = environ[i] + strlen(environ[i]) + 1;
  58. environ[i] = STRDUP(environ[i]);
  59. }
  60. else
  61. break;
  62. }
  63. arg_end = env_end;
  64. env_start = NULL;
  65. }
  66. i = arg_end - arg_start;
  67. if (tlen == i)
  68. {
  69. strncpy(arg_start, title, i);
  70. }
  71. else if (tlen < i)
  72. {
  73. strncpy(arg_start, title, i);
  74. memset(arg_start + tlen, 0, i - tlen);
  75. }
  76. else
  77. {
  78. *(char *)mempcpy(arg_start, title, i - 1) = '\0';
  79. }
  80. if (env_start)
  81. {
  82. p = strchr(arg_start, ' ');
  83. if (p)
  84. *p = '\0';
  85. }
  86. }
  87. void set_proc_name(const char *name)
  88. {
  89. prctl(PR_SET_NAME, name);
  90. }
  91. void get_proc_name(char *name)
  92. {
  93. prctl(PR_GET_NAME, name);
  94. }