1.使用dup2进行文件描述符的复制
(1)dup2和dup的作用是一样的,都是复制一个新的文件描述符,但是dup2允许用户指定新的文件描述符数字。
int dup2(int oldfd, int newfd);
第一个参数:久的文件描述符
第二个参数新的文件描述符
返回值:返回这个新的文件描述符
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FILENAME "2.txt"
int main(void)
{
int fd1 = -1;
int fd2 = -1;
char writeBuf[] = "asdjklajdqwe";
fd1 = open(FILENAME,O_RDWR | O_CREAT | O_TRUNC,0644);
if(fd1 < 0)
{
perror("open");
return -1;
}
printf("fd1 = %d\n",fd1);
fd2 = dup2(fd1,10);
printf("fd2 = %d\n",fd2);
write(fd1,writeBuf,10); //这两句为了验证它们是分别写还是接续写
write(fd2,writeBuf,10); //结果表面是接续写
close(fd1);
return 0;
}
返回的fd2 = 10;
2.dup2共享文件交叉写入测试
(1)dup2复制的文件描述符和原来的文件描述符虽然不一样,但是指向同一个文件。
(2)交叉写入的时候,验证结果是接续写
3.命令行重定位命令
(1)linux中的shell命令执行完过后,都是默认进入stdout在终端中直接显示,那我们怎么将ls、pwd等命令输出定位到一个文件中去。
ls > (文件名)
pwd > (文件名)
>:就是终端中的重定位符合