]> git.meshlink.io Git - catta/blob - avahi-daemon/setproctitle.c
make use of setproctitle() to change the process title of the daemon processes. This...
[catta] / avahi-daemon / setproctitle.c
1 /* $Id$ */
2
3 /***
4   This file is part of avahi.
5  
6   avahi is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10  
11   avahi is distributed in the hope that it will be useful, but WITHOUT
12   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
14   Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public
17   License along with avahi; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <unistd.h>
31
32 #include <avahi-common/malloc.h>
33
34 #include "setproctitle.h"
35
36 #if !defined(HAVE_SETPROCTITLE) && defined(__linux__)
37 static char** argv_buffer = NULL;
38 static size_t argv_size = 0;
39
40 #if !HAVE_DECL_ENVIRON
41 extern char **environ;
42 #endif
43
44 #endif
45
46 void avahi_init_proc_title(int argc, char **argv) {
47
48 #if !defined(HAVE_SETPROCTITLE) && defined(__linux__)
49
50     unsigned i;
51     char **new_environ, *endptr;
52
53     /* This code is really really ugly. We make some memory layout
54      * assumptions and reuse the environment array as memory to store
55      * our process title in */
56
57     for (i = 0; environ[i]; i++);
58
59     endptr = i ? environ[i-1] + strlen(environ[i-1]) : argv[argc-1] + strlen(argv[argc-1]);
60
61     argv_buffer = argv;
62     argv_size = endptr - argv_buffer[0];
63
64     /* Make a copy of environ */
65     
66     new_environ = avahi_malloc(sizeof(char*) * (i + 1));
67     for (i = 0; environ[i]; i++)
68         new_environ[i] = avahi_strdup(environ[i]);
69     new_environ[i] = NULL;
70
71     environ = new_environ;
72
73 #endif
74 }       
75
76 void avahi_set_proc_title(const char *fmt,...) {
77 #ifdef HAVE_SETPROCTITLE
78     char t[256];
79
80     va_list ap;
81     va_start(ap);
82     vsnprintf(t, sizeof(t), fmt, ap);
83     va_end(ap);
84
85     setproctitle("-%s", t);
86 #elif __linux__
87     size_t l;
88     va_list ap;
89     
90     if (!argv_buffer)
91         return;
92     
93     va_start(ap, fmt);
94     vsnprintf(argv_buffer[0], argv_size, fmt, ap);
95     va_end(ap);
96
97     l = strlen(argv_buffer[0]);
98     
99     memset(argv_buffer[0] + l, 0, argv_size - l);
100     argv_buffer[1] = NULL;
101 #endif
102 }