π₯ LETβS TRIGGER SOME KERNEL TEARS
π§ 03_read_closed_fd_trap
π£ read()
From a Closed FD
What happens if you try to read from an FD you already closed?
This vault entry shows how the kernel responds β and how you can catch and analyze it.
π 03_read_closed_fd_trap.c
(Simple, sharp, single-file trap)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(void)
{
int fd;
ssize_t rd;
char buf[32];
fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
printf("β
Opened FD %d\n", fd);
// Close it deliberately
close(fd);
printf("β Closed FD %d\n", fd);
// Try to read from the closed FD
rd = read(fd, buf, sizeof(buf));
if (rd == -1)
{
printf("π₯ read() failed as expected!\n");
printf("errno: %d (%s)\n", errno, strerror(errno));
}
else
{
printf("β οΈ Unexpectedly read %ld bytes: %.*s\n", rd, (int)rd, buf);
}
return (0);
}
π§ͺ Sample Output
β
Opened FD 3
β Closed FD 3
π₯ read() failed as expected!
errno: 9 (Bad file descriptor)
π§ Why This Matters
Concept | Insight |
---|---|
FD Lifetime | FDs are valid only while open. Use-after-close = undefined |
errno 9 | Standard error for invalid FD: EBADF |
Trap Point | Can happen in real life after complex dup2() or exec() cleanup |
Debugging | Perfect for scripting runtime FD sanity checks |
π What Youβll Learn
-
That closing a file descriptor doesnβt erase its number, but invalidates its FD table entry
-
That
read()
checks validity before syscall runs -
That reading from an invalid FD does not crash β it fails gracefully with
errno
π§° Pro Tips
-
Try to read from 0, 1, 2 after closing them π
-
Pipe this into
strace
:strace ./read_closed_fd_trap
β Ready to Run?
gcc 03_read_closed_fd_trap.c -o fdtrap && ./fdtrap
π Next Up Options?
-
π
[[04_fd_mirror_fanout]]
β duplicate a single FD into many and watch how close() affects all -
π§Ό
[[05_fd_exhaustion_test]]
β how many FDs can you open before your OS says βENOUGHβ -
π§ Or:
zombie_maker/
to trap unreaped children
Say the word β and the syscall abuse continues.
Youβre now writing syscall horror stories as a form of study π§ ππ