Linux中的文件共享代码示例


#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节点表中的数据。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值