Error Codes Wiki

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

  1. 1Use strace to trace file operations: strace -e openat,close,read,write ./program
  2. 2Check for double-close bugs: closing the same FD twice (second close returns EBADF)
  3. 3Verify open mode matches usage: O_RDONLY cannot write, O_WRONLY cannot read
  4. 4For multi-threaded code: ensure FD lifecycle is protected by locks or atomic operations
  5. 5Use Valgrind with --track-fds=yes to detect FD leaks and invalid FD usage

Tags

linuxebadferrno-9file-descriptorprogramming

More in Errno

Frequently 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.