Add documentation for para_select() and mark_fd_nonblock()
[paraslash.git] / fd.c
1 /*
2 * Copyright (C) 2006 Andre Noll <maan@systemlinux.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
17 */
18
19 /** \file fd.c helper functions for file descriptor handling */
20
21 #include "para.h"
22 #include "error.h"
23 /**
24 * check whether a file exists
25 *
26 * \param fn the file name
27 *
28 * \return Non-zero iff file exists.
29 */
30 int file_exists(const char *fn)
31 {
32 struct stat statbuf;
33
34 return !stat(fn, &statbuf);
35 }
36
37 /**
38 * paraslash's wrapper for select(2)
39 *
40 * It calls select(2) (with no exceptfds) and starts over if select() was
41 * interrupted by a signal.
42 *
43 * \param n the highest-numbered descriptor in any of the two sets, plus 1
44 * \param readfds fds that should be checked for readability
45 * \param writefds fds that should be checked for writablility
46 * \param timeout upper bound on the amount of time elapsed before select()
47 * returns
48 *
49 * \return The return value of the underlying select() call.
50 *
51 * All arguments are passed verbatim to select(2).
52 * \sa select(2) select_tut(2)
53 */
54 int para_select(int n, fd_set *readfds, fd_set *writefds,
55 struct timeval *timeout)
56 {
57 int ret, err;
58 do {
59 ret = select(n, readfds, writefds, NULL, timeout);
60 err = errno;
61 } while (ret < 0 && err == EINTR);
62 if (ret < 0)
63 PARA_CRIT_LOG("select error (%s)\n", strerror(err));
64 return ret;
65 }
66
67 /**
68 * set a file descriptor to non-blocking mode
69 *
70 * \param fd The file descriptor
71 *
72 * \returns 1 on success, -E_F_GETFL, -E_F_SETFL, on errors.
73 */
74 int mark_fd_nonblock(int fd)
75 {
76 int flags = fcntl(fd, F_GETFL);
77 if (flags < 0)
78 return -E_F_GETFL;
79 if (fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK) < 0)
80 return -E_F_SETFL;
81 return 1;
82 }
83