输入重定向 :more
输出重定向: cat file>result.txt
追加重定向: ls –l>>list.txt
错误重定向 :./myfile 2>err.txt
第一,标准I/O文件对应于最小的三个文件描述符
第二,最低可用文件描述符原则 即:当打开文件时,为此文件安排的描述符总是可用的文件描述符中值最小的。
第三,exec函数并不影响执行前打开的文件描述符集合。
//重定向方法一: close then open
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main(int argc,char *argv[]){ int fd; char buf[80]; read(0,buf,80); write(1,buf,80); close(0); fd=open("./tmp.txt",O_RDONLY); if(fd != 0){ perror("open"); exit(1); } read(0,buf,80); write(1,buf,80); return 0; }//重定向方法二: open…close…dup…close
dup函数: 功能:复制一个文件描述符
定义:int dup ( int oldfd ); 参数:oldfd 表示将要复制的文件描述符 返回值:-1,出错; >-1,表示新的文件描述符 dup遵循最低文件描述符原则,新复制的文件描述符和oldfd共用一个文件表项。 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc,char *argv[]){ int fd,newfd; char buf[80]; read(0,buf,80); write(1,buf,80); fd=open("./tmp.txt",O_RDONLY); close(0); newfd = dup(fd); if(newfd != 0){ perror("dup"); exit(1); } close(fd); read(0,buf,80); write(1,buf,80); return 0; }//重定向方法三 : open … dup2 … close
dup2 函数: 功能:复制一个文件描述符
定义:int dup ( int oldfd , int newfd ); 参数:oldfd 表示将要复制的文件描述符,newfd 表示复制后得到的新的文件描述符 返回值:-1,出错; >-1,表示新的文件描述符dup2在复制文件描述符时,如果newfd对应有打开的文件,那么系统会先关闭newfd,然后再复制。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc,char *argv[]){ int fd,newfd; char buf[80]; read(0,buf,80); write(1,buf,80); fd=open("./tmp.txt",O_RDONLY); if(fd != -1){ perror("open"); exit(1); } newfd = dup2(fd,0); if(newfd != 0){ perror("dup2"); exit(1); } close(fd); read(0,buf,80); write(1,buf,80); return 0; }//重定向方法四: 使用popen实现重定向
popen函数: 功能:建立一个指向进程的流
定义:FILE *popen(char *cmd, char * mode); 参数:cmd 要执行的进程 mode 使用进程的方式 返回值: 非NULL 指向进程的流指针 NULL 失败 #include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]){ FILE *fp; char buf[80]; int i=0; fp=popen("ls -l","r"); while(fgets(buf,80,fp) != NULL){ printf("%s\n",buf); } pclose(fp); return 0; }//示例: 实现 ls -l >list.txt
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc,int *argv[]){ int pid,fd; printf("This is show how ro redirect ! \n"); if((pid = fork()) == -1){ //进程创建失败 perror("fork"); exit(1); } else if(pid == 0){ //子进程 close(1); fd = creat("list.txt",0644); if(execlp("ls","ls -l",NULL) < 0){ perror("exec"); exit(1); } } else{ //父进程 if(pid != 0){ wait(NULL); system("cat list.txt"); } } return 0; }(1)创建命名管道:
mkfifio函数:功能:创建一条命名管道
定义:int mkfifo(char *filename, mode_t mode); 参数:filename 创建的FIFO文件名 mode 文件的权限模式 返回值:-1,出错; 0 ,成功(2)使用示例:
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc,char *argv[]){ int pid,fd; char buf[80]; mkfifo("fifotest",0644); if((pid = fork()) > 0){ fd=open("fifotest",O_WRONLY); write(fd,"Message to test FIFO!",22); close(fd); exit(0); } else if( pid == 0){ fd=open("fifotest",O_RDONLY); read(0,buf,80); printf("%s\n",buf); close(fd); exit(0); } else{# perror("fork"); exit(1); } return 0; }