chiark / gitweb /
Prep v228: Add remaining updates from upstream (3/3)
[elogind.git] / src / basic / fd-util.h
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 #pragma once
4
5 /***
6   This file is part of systemd.
7
8   Copyright 2010 Lennart Poettering
9
10   systemd is free software; you can redistribute it and/or modify it
11   under the terms of the GNU Lesser General Public License as published by
12   the Free Software Foundation; either version 2.1 of the License, or
13   (at your option) any later version.
14
15   systemd is distributed in the hope that it will be useful, but
16   WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18   Lesser General Public License for more details.
19
20   You should have received a copy of the GNU Lesser General Public License
21   along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 ***/
23
24 #include <stdio.h>
25 #include <dirent.h>
26 #include <stdbool.h>
27 #include <sys/socket.h>
28
29 #include "macro.h"
30
31 /* Make sure we can distinguish fd 0 and NULL */
32 #define FD_TO_PTR(fd) INT_TO_PTR((fd)+1)
33 #define PTR_TO_FD(p) (PTR_TO_INT(p)-1)
34
35 int close_nointr(int fd);
36 int safe_close(int fd);
37 void safe_close_pair(int p[]);
38
39 void close_many(const int fds[], unsigned n_fd);
40
41 int fclose_nointr(FILE *f);
42 FILE* safe_fclose(FILE *f);
43 DIR* safe_closedir(DIR *f);
44
45 static inline void closep(int *fd) {
46         safe_close(*fd);
47 }
48
49 static inline void close_pairp(int (*p)[2]) {
50         safe_close_pair(*p);
51 }
52
53 static inline void fclosep(FILE **f) {
54         safe_fclose(*f);
55 }
56
57 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, pclose);
58 DEFINE_TRIVIAL_CLEANUP_FUNC(DIR*, closedir);
59
60 #define _cleanup_close_ _cleanup_(closep)
61 #define _cleanup_fclose_ _cleanup_(fclosep)
62 #define _cleanup_pclose_ _cleanup_(pclosep)
63 #define _cleanup_closedir_ _cleanup_(closedirp)
64 #define _cleanup_close_pair_ _cleanup_(close_pairp)
65
66 int fd_nonblock(int fd, bool nonblock);
67 int fd_cloexec(int fd, bool cloexec);
68
69 int close_all_fds(const int except[], unsigned n_except);
70
71 int same_fd(int a, int b);
72
73 void cmsg_close_all(struct msghdr *mh);
74
75 bool fdname_is_valid(const char *s);