Safest way to force close a file descriptor
open /dev/null with O_WRONLY, then dup2 to close the offending file descriptor and reuse it's descriptor for /dev/null. This way any reads or writes to the file descriptor will fail.
If you dup a descriptor to /dev/null
, any writes will not fail, but succeed, and the reads will succeed and return 0 (eof).
This may or may not be what you want.
On linux, you can also open a file with flags = 3 (O_WRONLY|O_RDWR
aka O_NOACCESS
) which will cause any read or write to fail with EBADF
.
The file will only be available for ioctls -- which brings up a danger not talked about in the other answer and comments: reads and writes are not the only operations done on file descriptors. (what about lseek
or ftruncate
?).
Update:
I found something better than the undocumented O_WRONLY|O_RDWR
: O_PATH = 010000000 / 0x200000
. According to the open(2) manpage:
O_PATH (since Linux 2.6.39) Obtain a file descriptor that can be used for two purposes: to indicate a location in the filesystem tree and to perform opera- tions that act purely at the file descriptor level. The file itself is not opened, and other file operations (e.g., read(2), write(2), fchmod(2), fchown(2), fgetxattr(2), mmap(2)) fail with the error EBADF. The following operations can be performed on the resulting file descriptor: * close(2); fchdir(2) (since Linux 3.5); fstat(2) (since Linux 3.6). * Duplicating the file descriptor (dup(2), fcntl(2) F_DUPFD, etc.).