答案是肯定的,一个线程可以多次打开同一个文件,只是每次打开的fd值是不一样的。
这些fd都可以用于操作文件。
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
int main(char argc, char*argv[]) {
int fd=open("myfile",O_RDWR|O_CREAT,0644);
if(fd<0)
{
printf("open faild errno:%s\n",strerror(errno));
}
printf("open fd :%d\n",fd);
int fd1=open("myfile",O_RDWR|O_CREAT,0644);
if(fd1<0)
{
printf("open1 faild errno:%s\n",strerror(errno));
}
printf("open1 fd :%d\n",fd1);
if(fd >= 0)
close(fd);
if(fd1 >= 0)
close(fd1);
return 0;
}
open fd :3
open1 fd :4
注:其实文件没有close也问题不大,当进程结束时,系统会把所有打开的fd都关闭。