#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char *argv[])
{
int fd1;
int fd2;
char buf1[1024] = {0};
char buf2[1024] = {0};
fd1 = open("test.txt", O_RDONLY);
if (fd1 == -1)
ERR_EXIT("open error");
read(fd1, buf1, 5);
printf("buf1=%s\n", buf1);
fd2 = open("test.txt", O_RDWR);
if (fd2 == -1)
ERR_EXIT("open error");
read(fd2, buf2, 5);
printf("buf2=%s\n", buf2);
write(fd2, "CCCCCC", 6);
memset(buf1, 0, sizeof(buf1));
read(fd1, buf1, 5);
printf("buf1=%s\n", buf1);
close(fd1);
close(fd2);
return 0;
}
一个进程两次打开同一个文件,其中V节点信息是共享的
所以上述的例子中fd1和fd2 的两者分别读取文件的时偏移量是0,当通过fd2写入数据时6个CCCCCC,文件内容更改为abcdecccccc,再次用fd1读取文件时偏移量是从6开始,读取五个数据是ccccc。这说明两个文件描述符共享V节点表中的数据。