Linux EBADF (errno 9) — Bad File Descriptor
Warningerrno
Overview
Linux EBADF error occurs when a program tries to perform I/O on a file descriptor that is not open or not valid for the attempted operation.
Key Details
- EBADF (errno 9) means the file descriptor number is invalid or not open
- Common when reading from a closed file descriptor or writing to a read-only descriptor
- Can also occur when using select()/poll()/epoll() with invalid or closed descriptors
- In shell scripts: EBADF from redirection to a closed file descriptor
- Thread safety: one thread closing an FD while another is using it
Common Causes
- Using a file descriptor after it has been closed
- Writing to a file descriptor opened as read-only (or vice versa)
- Race condition: one thread closes FD while another reads/writes
- File descriptor reuse after close — new FD may have different semantics
- Shell script using a file descriptor number that was never opened
Steps
- 1Use strace to trace file operations: strace -e openat,close,read,write ./program
- 2Check for double-close bugs: closing the same FD twice (second close returns EBADF)
- 3Verify open mode matches usage: O_RDONLY cannot write, O_WRONLY cannot read
- 4For multi-threaded code: ensure FD lifecycle is protected by locks or atomic operations
- 5Use Valgrind with --track-fds=yes to detect FD leaks and invalid FD usage
Tags
linuxebadferrno-9file-descriptorprogramming
More in Errno
linux-errno-1-epermLinux errno 1 (EPERM) — Operation Not Permitted
Warninglinux-errno-2-enoentLinux errno 2 (ENOENT) — No Such File or Directory
Warninglinux-errno-5-eioLinux errno 5 (EIO) — Input/Output Error
Errorlinux-errno-11-eagainLinux errno 11 (EAGAIN) — Resource Temporarily Unavailable
Informationallinux-errno-12-enomemLinux errno 12 (ENOMEM) — Out of Memory
Criticallinux-errno-13-eaccesLinux errno 13 (EACCES) — Permission Denied
WarningFrequently Asked Questions
A small integer representing an open file, socket, or pipe. 0=stdin, 1=stdout, 2=stderr. Higher numbers are assigned for files you open.