π₯ LETβS FREAKING GO β into [[asymmetric_c/14_stdout_recursive_redirection/]]
ππ
π 14_stdout_recursive_redirection
π§ Project Idea
Recursive stdout redirection β a cursed experiment in dup2, descriptor mirroring, and unintended I/O recursion.
Weβre not just redirecting once.
Weβre layering and folding descriptors back onto each other to simulate a feedback loop.
This can manifest:
-
π Self-referential writes
-
πͺ Unexpected output behavior
-
π₯ Recursive flush + backpressure traps
π Files
mkdir -p asymmetric_c/14_stdout_recursive_redirection/
cd asymmetric_c/14_stdout_recursive_redirection/
touch stdout_feedback.c
π§ͺ stdout_feedback.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
// Debug macro
#define LOG(msg) write(STDOUT_FILENO, msg, sizeof(msg) - 1)
int main(void)
{
int fd_orig;
int fd_log;
int ret;
// Duplicate stdout to preserve original
fd_orig = dup(STDOUT_FILENO);
if (fd_orig < 0)
{
perror("dup");
exit(1);
}
// Open a log file
fd_log = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd_log < 0)
{
perror("open");
exit(1);
}
LOG("π redirecting stdout -> log.txt\n");
dup2(fd_log, STDOUT_FILENO);
close(fd_log);
LOG("π’ now writing to log.txt (stdout is redirected)\n");
// Redirect stdout back to original again
LOG("β οΈ this won't show in terminal yet!\n");
dup2(fd_orig, STDOUT_FILENO);
close(fd_orig);
LOG("β
stdout back to terminal\n");
return 0;
}
π§ Whatβs happening
title: Timeline of Descriptors
collapse: open
icon: πͺ
1. stdout originally points to the terminal (FD 1)
2. You save it as fd_orig
3. Redirect stdout to log.txt
4. Log goes into file
5. Restore stdout from fd_orig
6. Terminal again receives output
πͺ Blindspots to Observe
title: Questions for Reflection
-
What happens if you
dup2(fd_orig, fd_orig);
? -
What if you redirect stdout to
/dev/null
, then try to pipe from it? -
Does flushing behavior differ when writing to a regular file vs a TTY?
-
Could you recursively redirect between
stdout
andstderr
indefinitely? -
What if you close fd 1 before restoring?
π§ Strategic Commentary
This small but powerful test gives you:
-
β¨ Intuition for low-level I/O flow
-
π Real-world usage for
dup
,dup2
,open
-
π£ Traps youβll hit in
minishell
,pipex
, logging daemons -
π§© Insight into
stdout
vsstderr
logic
β Result
> gcc stdout_feedback.c -o feedback && ./feedback
π redirecting stdout -> log.txt
β
stdout back to terminal
Check log.txt
:
π’ now writing to log.txt (stdout is redirected)
β οΈ this won't show in terminal yet!
π§ Verdict
This project is done β
Want to add recursive stdout <-> stderr
loops in a cursed playground next?
Or move on to [[asymmetric_c/15_pipex_dag_graph_exec/]]
β where execution graphs get wild?
Say the word.