summaryrefslogtreecommitdiff
path: root/src/libstddjb/fd_ensure_open.c
blob: 4c1b63cd2fec4e373a5cea53abd7fa5d43f84ea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* ISC license. */

#include <errno.h>
#include <fcntl.h>

#include <skalibs/djbunix.h>

int fd_ensure_open (int fd, int w)
{
  int dummy ;
  if (fcntl(fd, F_GETFD, &dummy) == -1)
  {
    int newfd ;
    if (errno != EBADF) return 0 ;
    newfd = open2("/dev/null", w ? O_WRONLY : O_RDONLY) ;
    if (newfd == -1) return 0 ;
    if (fd_move(fd, newfd) == -1)
    {
      fd_close(newfd) ;
      return 0 ;
    }
  }
  return 1 ;
}