將stdin定向到文件有3種方法:
1.close then open .類似掛斷電話釋放一條線路,然后再將電話拎起來從而得到另一條線路。
先close(0);將標准輸入關掉,那么文件描述符數組中的第一個元素處於空閑狀態。(一般數組0=stdin, 1=stdout, 2=stderror,如果不關閉那么進程請求一個新的文件描述符的時候系統內核將最低可用的文件描述符給它,那么就是2以后的元素,關掉0,就分配了0給新進程)。
close(0); fd=open("/etc/passwd", O_RDONLY);
2.open..close..dup..close
先fd=open(file),打開stdin要重定向的文件,返回一文件描述符,不過它不是0,因為0還在當前被打開了。
close(0)關閉0
dup(fd),復制文件描述符fd,此次復制使用最低可用文件描述符號。因此獲得的是0.於是磁盤文件和0連接一起了。
close(fd).
3.open..dup2..close.
下面說說dup的函數
dup dup2
#include <fcntl.h>
newfd = dup(oldfd);
newfd = dup2(oldfd, newfd); oldfd需要復制的文件描述符,newfd復制oldfd后得到的文件描述符
return -1:error newfd:right
1 /* whotofile.c 2 * purpose: show how to redirect output for another program 3 * idea: fork, then in the child , redirect output , then exec 4 */ 5 #include <stdio.h> 6 #include <fcntl.h> 7 int main(void) { 8 int pid, fd; 9 printf("About to run the who.\n"); 10 if((pid=fork()) ==-1){ 11 perror("fork"); 12 exit(1); 13 } 14 if(pid==0) { 15 // close(1); 16 fd = creat("userlist", 0644); 17 close(1); 18 dup2(fd, 1); 19 execlp("who", "who", NULL); 20 perror("execlp"); 21 exit(1); 22 } 23 if(pid!=0) { 24 wait(0); 25 printf("Done running who. results in userlist.\n"); 26 } 27 return 0; 28 }
內核總是使用最低可用文件描述符;
文件描述符集合通過exec調用傳遞,而且不會被改變。