How to recover stdin overwritten by dup2?
You can't recover the original once it has been overwritten (closed). What you can do is save a copy of it before you overwrite it (which requires planning ahead, of course):
int old_stdin = dup(STDIN_FILENO);dup2(p, STDIN_FILENO);close(p); // Usually correct when you dup to a standard I/O file descriptor.…code using stdin…dup2(old_stdin, STDIN_FILENO);close(old_stdin); // Probably correctscanf(…);
However, your code mentions exec(…some commands…);
— if that is one of the POSIX execve()
family of functions, then you won't reach the scanf()
(or the second dup2()
) call unless the exec*()
call fails.