]> git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/setproctitle.c
whereis: use xstrncpy()
[thirdparty/util-linux.git] / lib / setproctitle.c
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 size_t 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 = 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 if (i > 0)
46 argv_lth = envp[i-1] + strlen(envp[i-1]) - argv[0];
47 else
48 argv_lth = argv[argc-1] + strlen(argv[argc-1]) - argv[0];
49 if (argv_lth > 1)
50 argv0 = argv;
51 }
52
53 void setproctitle (const char *prog, const char *txt)
54 {
55 size_t i;
56 char buf[SPT_BUFSIZE];
57
58 if (!argv0)
59 return;
60
61 if (strlen(prog) + strlen(txt) + 5 > SPT_BUFSIZE)
62 return;
63
64 sprintf(buf, "%s -- %s", prog, txt);
65
66 i = strlen(buf);
67 if (i > argv_lth - 2) {
68 i = argv_lth - 2;
69 buf[i] = '\0';
70 }
71 memset(argv0[0], '\0', argv_lth); /* clear the memory area */
72 strcpy(argv0[0], buf);
73
74 argv0[1] = NULL;
75 }