d904954ce5a47c00963006b4f652753f32ee6338
[src/app-framework-binder.git] / src / sd-fds.c
1 /*
2  Copyright 2017 IoT.bzh
3
4  author: José Bollo <jose.bollo@iot.bzh>
5
6  Licensed under the Apache License, Version 2.0 (the "License");
7  you may not use this file except in compliance with the License.
8  You may obtain a copy of the License at
9
10      http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  See the License for the specific language governing permissions and
16  limitations under the License.
17 */
18
19 #define _GNU_SOURCE
20
21 #include <assert.h>
22 #include <string.h>
23 #include <errno.h>
24
25 #include <systemd/sd-daemon.h>
26
27 static int init_done;
28 static char *null;
29 static char **names;
30
31 int sd_fds_init()
32 {
33         int rc;
34
35         if (init_done)
36                 rc = 0;
37         else {
38                 init_done = 1;
39                 rc = sd_listen_fds_with_names(1, &names);
40                 if (rc <= 0) {
41                         errno = -rc;
42                         rc = -!!rc;
43                         names = &null;
44                 }
45         }
46         return rc;
47 }
48
49 int sd_fds_count()
50 {
51         int count;
52
53         assert(init_done);
54         for (count = 0 ; names[count] != NULL ; count++);
55         return count;
56 }
57
58 int sd_fds_for(const char *name)
59 {
60         int idx;
61
62         assert(init_done);
63         for (idx = 0 ; names[idx] != NULL ; idx++)
64                 if (!strcmp(name, names[idx]))
65                         return idx + SD_LISTEN_FDS_START;
66
67         errno = ENOENT;
68         return -1;
69 }
70