Reputation: 169
I am trying to replace stdin with another pipe, then place the original stdin back to fd #0.
e.g.
dup2(p, 0); // p is a pre-existing fd of a pipe
exec(/* some commands */);
//what will be here in order to have the original stdin back?
scanf(...) //continue processing with original stdin.
Upvotes: 5
Views: 3438
Reputation: 754910
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 correct
scanf(…);
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.
Upvotes: 9