1/* Utility for handling interrupted syscalls by signals.
2
3   Copyright (C) 2020-2023 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#ifndef GDBSUPPORT_EINTR_H
21#define GDBSUPPORT_EINTR_H
22
23#include <cerrno>
24
25namespace gdb
26{
27/* Repeat a system call interrupted with a signal.
28
29   A utility for handling interrupted syscalls, which return with error
30   and set the errno to EINTR.  The interrupted syscalls can be repeated,
31   until successful completion.  This utility avoids wrapping code with
32   manual checks for such errors which are highly repetitive.
33
34   For example, with:
35
36   ssize_t ret;
37   do
38     {
39       errno = 0;
40       ret = ::write (pipe[1], "+", 1);
41     }
42   while (ret == -1 && errno == EINTR);
43
44   You could wrap it by writing the wrapped form:
45
46   ssize_t ret = gdb::handle_eintr (-1, ::write, pipe[1], "+", 1);
47
48   ERRVAL specifies the failure value indicating that the call to the
49   F function with ARGS... arguments was possibly interrupted with a
50   signal.  */
51
52template<typename ErrorValType, typename Fun, typename... Args>
53inline auto
54handle_eintr (ErrorValType errval, const Fun &f, const Args &... args)
55  -> decltype (f (args...))
56{
57  decltype (f (args...)) ret;
58
59  do
60    {
61      errno = 0;
62      ret = f (args...);
63    }
64  while (ret == errval && errno == EINTR);
65
66  return ret;
67}
68
69} /* namespace gdb */
70
71#endif /* GDBSUPPORT_EINTR_H */
72