Linux_C 输入输出重定向

将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调用传递,而且不会被改变。

posted on 2014-11-04 22:58  Zachary_wiz  阅读(4483)  评论(0编辑  收藏  举报

导航