summaryrefslogtreecommitdiff
path: root/lib/stdopen.c
blob: 6cf52189660604f07c05615c156f4b7b98778183 (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
25
26
27
28
29
30
31
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* Try to ensure that each of the standard file numbers (0, 1, 2)
   is in use.  Without this, each application would have to guard
   every call to open, dup, and fopen with tests to ensure they don't
   use one of the special file numbers when opening a user's file.  */
void
stdopen (void)
{
  int fd;
  for (fd = 0; fd <= 2; fd++)
    {
      struct stat sb;
      if (fstat (fd, &sb) < 0)
	{
	  static const int flag[] = { O_WRONLY, O_RDONLY, O_RDONLY };
	  /* FIXME: worry about errno != EBADF?  */
	  char const *file = "/dev/null";
	  int fd2 = open (file, flag[fd]);
	  if (fd2 < 0)
	    break;
	  if (fd2 != fd)
	    {
	      close (fd2);
	      break;
	    }
	}
    }
}