1207753Smm/////////////////////////////////////////////////////////////////////////////// 2207753Smm// 3207753Smm/// \file tuklib_open_stdxxx.c 4207753Smm/// \brief Make sure that file descriptors 0, 1, and 2 are open 5207753Smm// 6207753Smm// Author: Lasse Collin 7207753Smm// 8207753Smm// This file has been put into the public domain. 9207753Smm// You can do whatever you want with this file. 10207753Smm// 11207753Smm/////////////////////////////////////////////////////////////////////////////// 12207753Smm 13207753Smm#include "tuklib_open_stdxxx.h" 14207753Smm 15207753Smm#ifndef TUKLIB_DOSLIKE 16207753Smm# include <stdlib.h> 17207753Smm# include <errno.h> 18207753Smm# include <fcntl.h> 19207753Smm# include <unistd.h> 20207753Smm#endif 21207753Smm 22207753Smm 23207753Smmextern void 24207753Smmtuklib_open_stdxxx(int err_status) 25207753Smm{ 26207753Smm#ifdef TUKLIB_DOSLIKE 27207753Smm // Do nothing, just silence warnings. 28207753Smm (void)err_status; 29207753Smm 30207753Smm#else 31207753Smm for (int i = 0; i <= 2; ++i) { 32207753Smm // We use fcntl() to check if the file descriptor is open. 33207753Smm if (fcntl(i, F_GETFD) == -1 && errno == EBADF) { 34207753Smm // With stdin, we could use /dev/full so that 35207753Smm // writing to stdin would fail. However, /dev/full 36207753Smm // is Linux specific, and if the program tries to 37207753Smm // write to stdin, there's already a problem anyway. 38207753Smm const int fd = open("/dev/null", O_NOCTTY 39207753Smm | (i == 0 ? O_WRONLY : O_RDONLY)); 40207753Smm 41207753Smm if (fd != i) { 42223935Smm if (fd != -1) 43223935Smm (void)close(fd); 44223935Smm 45207753Smm // Something went wrong. Exit with the 46207753Smm // exit status we were given. Don't try 47207753Smm // to print an error message, since stderr 48207753Smm // may very well be non-existent. This 49207753Smm // error should be extremely rare. 50207753Smm exit(err_status); 51207753Smm } 52207753Smm } 53207753Smm } 54207753Smm#endif 55207753Smm 56207753Smm return; 57207753Smm} 58