EBADF
Linux / POSIXERRORNotableFile SystemHIGH confidence
Bad File Descriptor
What this means
An operation was attempted on a file descriptor that is not open or is invalid. This commonly occurs after a double-close bug, using a descriptor after the file was closed, or using a read-only descriptor for writing.
Why it happens
- 1The file descriptor was already closed (double-close bug).
- 2The descriptor number is negative or beyond the process limit.
- 3Attempting to write to a file descriptor opened with O_RDONLY.
- 4Using a file descriptor after fork() in the child process when it was not meant to be inherited.
How to reproduce
Reading from a file descriptor after it has been closed.
trigger — this will error
trigger — this will error
int fd = open("/tmp/test.txt", O_RDONLY);
close(fd);
// fd is now invalid
char buf[64];
read(fd, buf, sizeof(buf)); // returns -1, errno = EBADFexpected output
read() returned -1, errno = EBADF (Bad file descriptor)
Fix
Set descriptor to -1 after closing
WHEN In C/C++ code that might close a descriptor and later reference it
Set descriptor to -1 after closing
close(fd);
fd = -1; // prevent accidental reuse
// Later:
if (fd >= 0) { read(fd, buf, n); }Why this works
Setting fd to -1 after close makes subsequent validity checks fail safely instead of operating on a recycled descriptor.
Sources
Official documentation ↗
Linux Programmer Manual errno(3)
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev