proc_title.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. int tlen = strlen(title) + 1;
  44. int i;
  45. char *p;
  46. if (arg_start == NULL)
  47. return;
  48. if (arg_end - arg_start < tlen && env_start == arg_end)
  49. {
  50. char *env_end = env_start;
  51. for (i = 0; environ[i]; i++)
  52. {
  53. if (env_end == environ[i])
  54. {
  55. env_end = environ[i] + strlen(environ[i]) + 1;
  56. environ[i] = STRDUP(environ[i]);
  57. }
  58. else
  59. break;
  60. }
  61. arg_end = env_end;
  62. env_start = NULL;
  63. }
  64. i = arg_end - arg_start;
  65. if (tlen == i)
  66. {
  67. strncpy(arg_start, title, i);
  68. }
  69. else if (tlen < i)
  70. {
  71. strncpy(arg_start, title, i);
  72. memset(arg_start + tlen, 0, i - tlen);
  73. }
  74. else
  75. {
  76. *(char *)mempcpy(arg_start, title, i - 1) = '\0';
  77. }
  78. if (env_start)
  79. {
  80. p = strchr(arg_start, ' ');
  81. if (p)
  82. *p = '\0';
  83. }
  84. }
  85. void set_proc_name(const char *name)
  86. {
  87. prctl(PR_SET_NAME, name);
  88. }
  89. void get_proc_name(char *name)
  90. {
  91. prctl(PR_GET_NAME, name);
  92. }