簡體   English   中英

如何恢復被dup2覆蓋的stdin?

[英]How to recover stdin overwritten by dup2?

我試圖用另一個管道替換stdin,然后將原始stdin放回到fd#0。

例如

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.

一旦被覆蓋(關閉),您就無法恢復原始狀態。 您可以做的是在覆蓋它之前保存它的副本(當然需要提前計划):

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(…);

但是,你的代碼提到了exec(…some commands…); - 如果它是POSIX execve()系列函數之一,那么除非exec*()調用失敗,否則你不會到達scanf() (或第二個dup2() )調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM