1.什么是文件描述符
文件描述就是打开文件内核数据结构,返回给用户的一个整数。
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("./log.txt",O_WRONLY|O_CREAT,0644);
if(fd < 0)
printf("opern");
printf("%d\n",fd);
}

我们打开文件会给我打开一个文件描述符,为什么会是3呢
因为操作系统会给每个进程打开3个文件描述符
0.标准输出 1.标准输入 2.标准错误
为了弄清文件描述符的本质,我们需要了解操作系统是怎么维护这些文件的,
大家有没有想过,为什么在Linux上一切皆文件,包括显示器和键盘都是文件,磁盘文件我可以读写,显示器文件可以读写吗,答案是肯定的。下面我会讲解Linux 上为什么一切皆文件。当然小编不是凭空猜测,我们接下里就看看内核源码。

2.什么是重定向
1.输出重定向
本来从键盘输出,变成从文件输出。
在此之前我需要知道,Linux 开打文件每次都是重最小的位置,填入。举个例子
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include <fcntl.h>
int main()
{
close(0);
int fd = open("./log.txt",O_WRONLY|O_CREAT,0644);
if(fd < 0)
printf("opern");
printf("%d\n",fd);
}
?
我们关掉文件描述符0,在创建文件,此时文件描述就是0,了

这就是输出重定向
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include <fcntl.h>
int main()
{
close(1);
char buf[128];
int fd = open("./log.txt",O_WRONLY|O_CREAT,0644);
printf("%d\n",fd);
}
?此时本来改打印到屏幕的内容打印到了文件log.txt

?dup2的运用
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include <fcntl.h>
int main()
{
char buf[128];
int fd = open("./log.txt",O_WRONLY|O_CREAT,0644);
dup2(fd,1);
printf("%d\n",fd);
}
本应该输出到屏幕的内容,输出到了log.txt

?3.子进程和父进程共享文件描述符

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<wait.h>
#include <fcntl.h>
int main()
{
if(fork() == 0)
{
int fd = open("./log.txt",O_WRONLY|O_CREAT,0644);
write(fd,"hello wrold",11);
exit(1);
}
waitpid(-1,NULL,0);
char buf[128];
int fd = open("./log.txt",O_RDONLY);
read(3,buf,11);
buf[12] = 0;
printf("%s\n",buf);
}
?子进程修改了文件log.txt,父进程打印hello wrold
4.关于stdin,stdout,strerr
我们在FILE这个结构体中可以找到文件描述符、在、usr/include/stdio.h中
?那我们可以打印文件描述符
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<wait.h>
#include <fcntl.h>
int main()
{
printf("%d\n",stdin->_fileno);
printf("%d\n",stdout->_fileno);
printf("%d\n",stderr->_fileno);
}

?所以我们可以看出上层调用最好一定要走系统调用,所以不管什么软件,程序,都必需要使用系统调用,所以我们一定要学好Linux系统编程
|