fff246fb6ebc4762269b0ad3f34eefb228bfb33e
[src/app-framework-binder.git] / src / process-name.c
1 /*
2  * Copyright (C) 2015-2019 "IoT.bzh"
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
17 #include <string.h>
18 #include <unistd.h>
19 #include <errno.h>
20 #include <sys/prctl.h>
21
22 #include "process-name.h"
23
24 int process_name_set_name(const char *name)
25 {
26         return prctl(PR_SET_NAME, name);
27 }
28
29 int process_name_replace_cmdline(char **argv, const char *name)
30 {
31         char *beg, *end, **av, c;
32
33         /* update the command line */
34         av = argv;
35         if (!av) {
36                 errno = EINVAL;
37                 return -1; /* no command line update required */
38         }
39
40         /* longest prefix */
41         end = beg = *av;
42         while (*av)
43                 if (*av++ == end)
44                         while(*end++)
45                                 ;
46         if (end == beg) {
47                 errno = EINVAL;
48                 return -1; /* nothing to change */
49         }
50
51         /* patch the command line */
52         av = &argv[1];
53         end--;
54         while (beg != end && (c = *name++)) {
55                 if (c != ' ' || !*av)
56                         *beg++ = c;
57                 else {
58                         *beg++ = 0;
59                         *av++ = beg;
60                 }
61         }
62         /* terminate last arg */
63         if (beg != end)
64                 *beg++ = 0;
65         /* update remaining args (for keeping initial length correct) */
66         while (*av)
67                 *av++ = beg;
68         /* fulfill last arg with spaces */
69         while (beg != end)
70                 *beg++ = ' ';
71         *beg = 0;
72
73         return 0;
74 }
75