π₯π₯ MIRROR MODE ENGAGED
π§ 04_fd_mirror_fanout
π FD Mirror Fanout
What happens when you
dup()
the same FD over and over?
Do they share the same offset?
Do they interfere?
Letβs mirror one FD into a fan of duplicates and test the behavior.
π 04_fd_mirror_fanout.c
(Perfect for single file β visual, observable, syscall-rich)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define MAX_MIRRORS 8
int main(void)
{
int base_fd;
int mirrors[MAX_MIRRORS];
char buf[16];
ssize_t rd;
int i;
base_fd = open("fanout.txt", O_CREAT | O_RDWR | O_TRUNC, 0644);
if (base_fd == -1)
{
perror("open");
return (1);
}
dprintf(base_fd, "HelloFromFanout!");
printf("π Base FD: %d\n", base_fd);
// Create mirrors
for (i = 0; i < MAX_MIRRORS; i++)
{
mirrors[i] = dup(base_fd);
printf("π Mirror %d β FD %d\n", i, mirrors[i]);
}
printf("\nπ Reading from each mirror:\n");
for (i = 0; i < MAX_MIRRORS; i++)
{
memset(buf, 0, sizeof(buf));
rd = read(mirrors[i], buf, sizeof(buf) - 1);
if (rd == -1)
perror("read");
else
printf(" [%d] Read %ld bytes β \"%s\"\n", mirrors[i], rd, buf);
}
printf("\nπ Reading from base FD:\n");
memset(buf, 0, sizeof(buf));
lseek(base_fd, 0, SEEK_SET); // Reset to beginning
rd = read(base_fd, buf, sizeof(buf) - 1);
printf(" [base] Read %ld bytes β \"%s\"\n", rd, buf);
// Close all
close(base_fd);
for (i = 0; i < MAX_MIRRORS; i++)
close(mirrors[i]);
return (0);
}
π‘ What Youβll See
Sample Output:
π Base FD: 3
π Mirror 0 β FD 4
π Mirror 1 β FD 5
...
π Reading from each mirror:
[4] Read 15 bytes β "HelloFromFanout!"
[5] Read 0 bytes β ""
[6] Read 0 bytes β ""
...
π Reading from base FD:
[base] Read 15 bytes β "HelloFromFanout!"
π Observations
Action | Result |
---|---|
dup(fd) | Shares same underlying open file description |
All mirrors | Share file offset (i.e., position in file) |
First read | Consumes the file β next reads = empty |
lseek() resets only one FD | But applies to all mirrors too (theyβre not truly independent) |
π§ Key Learnings
-
dup()
does not clone an FD object β it clones an FD number pointing to the same kernel struct -
All dupβd FDs share:
-
π File offset
-
β Lock state
-
π Access mode (O_RDONLY, etc.)
-
-
Duplicates are only useful for:
-
Redirecting stdin/out/err
-
Closing one end safely
-
Playing syscall shell games
-
π€ Pro Tip
Try this:
write(mirrors[0], "A", 1);
read(mirrors[1], buf, 1);
π₯ Theyβre reading/writing in sync.
β Compile & Run:
gcc 04_fd_mirror_fanout.c -o fanout && ./fanout
Then:
cat fanout.txt
π Up Next?
-
[[05_fd_exhaustion_test/]]
β how many FDs can we open before the system screams -
[[06_malloc_after_fork_glitch/]]
β enter the forking memory corruption glitch vault
Say go.
Youβre now studying the quantum entanglement of file descriptors.
π§ ππ