bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 1 | /* |
| 2 | * set process title for ps (from sendmail) |
| 3 | * |
| 4 | * Clobbers argv of our main procedure so ps(1) will display the title. |
| 5 | */ |
| 6 | #include <stdio.h> |
| 7 | #include <stdlib.h> |
| 8 | #include <string.h> |
| 9 | #include <stdarg.h> |
| 10 | |
| 11 | #include "setproctitle.h" |
| 12 | |
| 13 | #ifndef SPT_BUFSIZE |
| 14 | # define SPT_BUFSIZE 2048 |
| 15 | #endif |
| 16 | |
| 17 | extern char **environ; |
| 18 | |
| 19 | static char **argv0; |
| 20 | static int argv_lth; |
| 21 | |
| 22 | void initproctitle (int argc, char **argv) |
| 23 | { |
| 24 | int i; |
| 25 | char **envp = environ; |
| 26 | |
| 27 | /* |
| 28 | * Move the environment so we can reuse the memory. |
| 29 | * (Code borrowed from sendmail.) |
| 30 | * WARNING: ugly assumptions on memory layout here; |
| 31 | * if this ever causes problems, #undef DO_PS_FIDDLING |
| 32 | */ |
| 33 | for (i = 0; envp[i] != NULL; i++) |
| 34 | continue; |
| 35 | |
| 36 | environ = (char **) malloc(sizeof(char *) * (i + 1)); |
| 37 | if (environ == NULL) |
| 38 | return; |
| 39 | |
| 40 | for (i = 0; envp[i] != NULL; i++) |
| 41 | if ((environ[i] = strdup(envp[i])) == NULL) |
| 42 | return; |
| 43 | environ[i] = NULL; |
| 44 | |
| 45 | argv0 = argv; |
| 46 | if (i > 0) |
| 47 | argv_lth = envp[i-1] + strlen(envp[i-1]) - argv0[0]; |
| 48 | else |
| 49 | argv_lth = argv0[argc-1] + strlen(argv0[argc-1]) - argv0[0]; |
| 50 | } |
| 51 | |
| 52 | void setproctitle (const char *prog, const char *txt) |
| 53 | { |
| 54 | int i; |
| 55 | char buf[SPT_BUFSIZE]; |
| 56 | |
| 57 | if (!argv0) |
| 58 | return; |
| 59 | |
| 60 | if (strlen(prog) + strlen(txt) + 5 > SPT_BUFSIZE) |
| 61 | return; |
| 62 | |
| 63 | sprintf(buf, "%s -- %s", prog, txt); |
| 64 | |
| 65 | i = strlen(buf); |
| 66 | if (i > argv_lth - 2) { |
| 67 | i = argv_lth - 2; |
| 68 | buf[i] = '\0'; |
| 69 | } |
| 70 | memset(argv0[0], '\0', argv_lth); /* clear the memory area */ |
| 71 | strcpy(argv0[0], buf); |
| 72 | |
| 73 | argv0[1] = NULL; |
| 74 | } |