1.close函数
close用来关闭文件描述符。
#include <unistd.h>
int close(int fd);
实例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
int main(int argc,char const *argv[]){
int fd;
//打开的文件test.txt不存在。
fd = open("test.txt", O_RDONLY | O_CREAT,0664);
if(fd==-1){
//printf("errno=%d\n", errno);
perror("fail open file:");
return -1;
}
//关闭文件
close(fd);
printf("文件关闭成功!");
return 0;
}
运行结果:
文件关闭成功!
2.关于文件描述符的规律
文件描述符fd是Linux相对有限的资源,单个进程中的fd数量有限制,一般默认是1024。
查看当前session的fd数量限制
# ulimit -n
实例:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
int main(int argc, char const *argv[])
{
int fd;
//打开的文件test.txt不存在。
while (1)
{
fd = open("test.txt", O_RDONLY | O_CREAT, 0664);
if (fd == -1)
{
perror("fail open file:");
break;
}
printf("fd=%d\n", fd);
}
return 0;
}
测试运行:
...
fd=2044
fd=2045
fd=2046
fd=2047
fail open file:: Too many open files
文件描述符一定是从小到大连续分配的,最后分配的文件描述符不一定就是最大的。 实例:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
int main(int argc, char const *argv[])
{
int fd1, fd2, fd3, fd4;
fd1 = open("test.txt", O_RDONLY | O_CREAT, 0664);
fd2 = open("test.txt", O_RDONLY | O_CREAT, 0664);
fd3 = open("test.txt", O_RDONLY | O_CREAT, 0664);
fd4 = open("test.txt", O_RDONLY | O_CREAT, 0664);
printf("fd1=%d\n", fd1);
printf("fd2=%d\n", fd2);
printf("fd3=%d\n", fd3);
printf("fd4=%d\n", fd4);
close(fd2);
int fd5, fd6;
fd5 = open("test.txt", O_RDONLY | O_CREAT, 0664);
fd6 = open("test.txt", O_RDONLY | O_CREAT, 0664);
printf("-----------------\n");
printf("fd1=%d\n", fd1);
printf("fd3=%d\n", fd3);
printf("fd4=%d\n", fd4);
printf("fd5=%d\n", fd5);
printf("fd6=%d\n", fd6);
return 0;
}
运行结果:
fd1=3
fd2=4
fd3=5
fd4=6
-----------------
fd1=3
fd3=5
fd4=6
fd5=4
fd6=7