学习自李慧琴老师
实验1:fclose
实验2:一个进程的空间中最多可以打开多少个文件
实验3:我们以 w 等的模式创建打开了一个文件,运行后得到 tmp文件,该文件的权限是怎么得到的
fclose:
AME
fclose - close a stream
SYNOPSIS
#include <stdio.h>
int fclose(FILE *stream);
RETURN VALUE
Upon successful completion 0 is returned. Otherwise, EOF is returned and errno is set to indicate the error. In either case any further access (including another call to fclose()) to the stream results in undefined behavior.
实验1:fclose
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE *fp;
//
fp = fopen("tmp","w");
if(fp == NULL)
{
fprintf(stderr,"fopen() failed! errno = %d\n",errno);
perror("fopen()");
fprintf(stderr,"fopen():%s\n",strerror(errno));
exit(1);
}
puts("OK!");
fclose(fp);
exit(0);
}
mhr@ubuntu:~/work/linux/stdio$ gcc fclose.c
mhr@ubuntu:~/work/linux/stdio$ ll
total 28
drwxrwxr-x 2 mhr mhr 4096 Apr 18 22:19 ./
drwxrwxr-x 3 mhr mhr 4096 Apr 16 08:28 ../
-rwxrwxr-x 1 mhr mhr 9024 Apr 18 22:19 a.out*
-rw-rw-r-- 1 mhr mhr 327 Apr 18 22:19 fclose.c
-rw-rw-r-- 1 mhr mhr 327 Apr 18 22:18 fopen.c
mhr@ubuntu:~/work/linux/stdio$ ./a.out
OK!
mhr@ubuntu:~/work/linux/stdio$
实验2:一个进程的空间中最多可以打开多少个文件
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
int count = 0;
FILE *fp=NULL;
//
while(1)
{
fp = fopen("tmp","r");
if(fp == NULL)
{
perror("fopen()");
break;
}
count++;
}
printf("count = %d\n",count);
exit(0);
}
mhr@ubuntu:~/work/linux/stdio$ gcc maxfopen.c
mhr@ubuntu:~/work/linux/stdio$ ./a.out
fopen(): Too many open files
count = 1021
mhr@ubuntu:~/work/linux/stdio$
mhr@ubuntu:~/work/linux/stdio$
程序显示进程最多打开了1021个文件,那么一个进程就最多只能代开1021个文件吗?实际上不是的,在不更改当前默认环境的情况下,一个进程默认会打开三个流。标准输入stdin,标准输出stdout,标准错误stderr,所以当前环境下一个进程最多可以打开 1021+3=1024个文件。
用命令 ulimit -a 可以查看当前环境下一个进程最多可以打开多少个文件
open files (-n) 1024
如果需要修改当前环境下,一个进程最大可以打开的文件数,执行 ulimit -n 1234 即可。
实验3:我们以 w 等的模式创建打开了一个文件,运行后得到 tmp文件,该文件的权限是怎么得到的
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE *fp;
//
fp = fopen("tmp","w");
if(fp == NULL)
{
fprintf(stderr,"fopen() failed! errno = %d\n",errno);
perror("fopen()");
fprintf(stderr,"fopen():%s\n",strerror(errno));
exit(1);
}
puts("OK!");
fclose(fp);
exit(0);
}
运行后得到 tmp文件,该文件的权限如下:664
mhr@ubuntu:~/work/linux/stdio$ ll
total 32
drwxrwxr-x 2 mhr mhr 4096 Apr 18 22:38 ./
drwxrwxr-x 3 mhr mhr 4096 Apr 16 08:28 ../
-rwxrwxr-x 1 mhr mhr 9024 Apr 18 22:38 a.out*
-rw-rw-r-- 1 mhr mhr 327 Apr 18 22:37 fopen.c
-rw-rw-r-- 1 mhr mhr 0 Apr 18 22:38 tmp
mhr@ubuntu:~/work/linux/stdio$
mhr@ubuntu:~/work/linux/stdio$ umask
0002
mhr@ubuntu:~/work/linux/stdio$
那么以不同的模式创建打开一个文件,w/w+/a/a+,创建出来的文件与fopen()时候指定的模式有什么关系吗?
遵循如下公式:0666 & ~umask, umask=0002
umask机制的存在就是为了防止产生权限过松的文件,从公式可以看出来,umask的权限越大,那么创建生成的文件的权限就越小。