[英]What does dup2() do in C
我在手冊頁中查了一下,但我仍然沒有得到它......
假設你有dup2(f1,0)
。 是否用stdin切換filedesc.1然后鎖定stdin?
dup2
不會切換文件描述符,它使它們等效。 在dup2(f1, 0)
,在描述符f1
上打開的任何文件現在也在描述符0上打開(具有相同的模式和位置),即在標准輸入上。
如果目標文件描述符(此處為0)已打開,則由dup2
調用關閉。 從而:
before after
0: closed, f1: somefile 0: somefile, f1:somefile
0: otherfile, f1: somefile 0: somefile, f1:somefile
不涉及鎖定。
當您擁有從標准文件描述符讀取或寫入的程序的一部分時, dup2
非常有用(除其他外)。 例如,假設somefunc()
從標准輸入讀取,但您希望它從其他程序獲取其標准輸入的其他文件中讀取。 然后你可以做(省略錯誤檢查):
int save_stdin = dup(0);
int somefunc_input_fd = open("input-for-somefunc.data", O_RDONLY);
dup2(somefunc_input_fd, 0);
/* Now the original stdin is open on save_stdin, and input-for-somefunc.data on both somefunc_input_fd and 0. */
somefunc();
close(somefunc_input_fd);
dup2(save_stdin, 0);
close(save_stdin);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.