2007-12-08 17:42:33 -05:00
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
//
|
2009-09-19 02:47:30 -04:00
|
|
|
/// \file tuklib_open_stdxxx.c
|
2007-12-08 17:42:33 -05:00
|
|
|
/// \brief Make sure that file descriptors 0, 1, and 2 are open
|
|
|
|
//
|
2009-04-13 04:27:40 -04:00
|
|
|
// Author: Lasse Collin
|
2007-12-08 17:42:33 -05:00
|
|
|
//
|
2009-04-13 04:27:40 -04:00
|
|
|
// This file has been put into the public domain.
|
|
|
|
// You can do whatever you want with this file.
|
2007-12-08 17:42:33 -05:00
|
|
|
//
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2009-09-19 02:47:30 -04:00
|
|
|
#include "tuklib_open_stdxxx.h"
|
2007-12-08 17:42:33 -05:00
|
|
|
|
2009-09-19 02:47:30 -04:00
|
|
|
#ifndef TUKLIB_DOSLIKE
|
|
|
|
# include <stdlib.h>
|
|
|
|
# include <errno.h>
|
|
|
|
# include <fcntl.h>
|
|
|
|
# include <unistd.h>
|
|
|
|
#endif
|
2007-12-08 17:42:33 -05:00
|
|
|
|
|
|
|
|
2009-09-19 02:47:30 -04:00
|
|
|
extern void
|
|
|
|
tuklib_open_stdxxx(int err_status)
|
2007-12-08 17:42:33 -05:00
|
|
|
{
|
2010-01-27 09:42:11 -05:00
|
|
|
#ifdef TUKLIB_DOSLIKE
|
|
|
|
// Do nothing, just silence warnings.
|
|
|
|
(void)err_status;
|
|
|
|
|
|
|
|
#else
|
2007-12-08 17:42:33 -05:00
|
|
|
for (int i = 0; i <= 2; ++i) {
|
|
|
|
// We use fcntl() to check if the file descriptor is open.
|
|
|
|
if (fcntl(i, F_GETFD) == -1 && errno == EBADF) {
|
|
|
|
// With stdin, we could use /dev/full so that
|
|
|
|
// writing to stdin would fail. However, /dev/full
|
|
|
|
// is Linux specific, and if the program tries to
|
|
|
|
// write to stdin, there's already a problem anyway.
|
|
|
|
const int fd = open("/dev/null", O_NOCTTY
|
|
|
|
| (i == 0 ? O_WRONLY : O_RDONLY));
|
|
|
|
|
|
|
|
if (fd != i) {
|
2011-05-28 09:43:26 -04:00
|
|
|
if (fd != -1)
|
|
|
|
(void)close(fd);
|
|
|
|
|
2007-12-08 17:42:33 -05:00
|
|
|
// Something went wrong. Exit with the
|
|
|
|
// exit status we were given. Don't try
|
|
|
|
// to print an error message, since stderr
|
|
|
|
// may very well be non-existent. This
|
|
|
|
// error should be extremely rare.
|
2009-09-19 02:47:30 -04:00
|
|
|
exit(err_status);
|
2007-12-08 17:42:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2009-09-19 02:47:30 -04:00
|
|
|
#endif
|
2007-12-08 17:42:33 -05:00
|
|
|
|
|
|
|
return;
|
|
|
|
}
|