Add option --name for naming the process
[src/app-framework-binder.git] / src / process-name.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "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         size_t length;
33
34         /* update the command line */
35         av = argv;
36         if (!av) {
37                 errno = EINVAL;
38                 return -1; /* no command line update required */
39         }
40
41         /* longest prefix */
42         end = beg = *av;
43         while (*av)
44                 if (*av++ == end)
45                         while(*end++)
46                                 ;
47         if (end == beg) {
48                 errno = EINVAL;
49                 return -1; /* nothing to change */
50         }
51
52         /* patch the command line */
53         av = &argv[1];
54         end--;
55         while (beg != end && (c = *name++)) {
56                 if (c != ' ' || !*av)
57                         *beg++ = c;
58                 else {
59                         *beg++ = 0;
60                         *av++ = beg;
61                 }
62         }
63         /* terminate last arg */
64         if (beg != end)
65                 *beg++ = 0;
66         /* update remaining args (for keeping initial length correct) */
67         while (*av)
68                 *av++ = beg;
69         /* fulfill last arg with spaces */
70         while (beg != end)
71                 *beg++ = ' ';
72         *beg = 0;
73
74         return 0;
75 }
76