将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
/* whotofile.c
* purpose: show how to redirect output for another program
* idea: fork, then in the child , redirect output , then exec
*/
#include <stdio.h>
#include <fcntl.h>
int main(void) {
int pid, fd;
printf("About to run the who.\n");
if((pid=fork()) ==-1){
perror("fork");
exit(1);
}
if(pid==0) {
// close(1);
fd = creat("userlist", 0644);
close(1);
dup2(fd, 1);
execlp("who", "who", NULL);
perror("execlp");
exit(1);
}
if(pid!=0) {
wait(0);
printf("Done running who. results in userlist.\n");
}
return 0;
}内核总是使用最低可用文件描述符;
文件描述符集合通过exec调用传递,而且不会被改变。
https://www.cnblogs.com/wizzhangquan/p/4075115.html
最新评论: