linux操作系统

linux操作系统 -重在理解

C库IO函数工作流程

image

pcb和文件描述符

image

虚拟地址空间

image

库函数与系统函数的关系

image

虚拟地址空间

cpu为什么要使用虚拟地址空间与物理地址空间映射?解决了什么样的问题?

1.方便编译器和操作系统安排程序的地址分布。
程序可以使用一系列相邻的虚拟地址来访问物理内存中不相邻的大内存缓冲区。

2.方便进程之间隔离不同进程使用的虚拟地址彼此隔离。
一个进程中的代码无法更改正在由另一进程使用的物理内存。

3.方便OS使用你那可怜的内存。
程序可以使用一系列虚拟地址来访问大于可用物理内存的内存缓冲区。
当物理内存的供应量变小时,内存管理器会将物理内存页(通常大小为 4 KB)保存到磁盘文件。数据或代码页会根据需要在物理内存与磁盘之间移动。

open函数代码示例

点击查看代码
// 打开已经存在文件
fd=open("hello.c",O_RDWR);

//创建新文件
fd=open("myhello",O_RDWR|O_CREAT,0777);

// 判断文件是否存在-方法之一
fd=open("myhello",O_RDWR|O_CREAT|O_EXCL,0777);

//将文件截断为0
fd=open("myhello",O_RDWR|O_TRUNC);

文件权限与代码指定不一致的解释

image

read write open综合使用

// 通过read读文件,将读取的内容写到(write)新文件之内

点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char* argv[])
{
	// 打开一个已经存在文件
 	int fd=open("english.txt",O_RDONLY);
	if(fd==-1)
	{
		perror("open english.txt file");
		exit(1);
	}
	// 创建一个新文件 写操作
	int fd1=open("newfile",O_CREAT|O_WRONLY);
	if(fd1==-1)
	{
		perror("open file");
		exit(1);
	}
	//read file
	char buf[2048]={0};
	int count = read(fd, buf, sizeof(buf));
	if(count == -1)
	{
		perror("read file");
		exit(1);
	}
	int ret = 0;
	while(count)
	{
		//将读取的内容写入到另一个文件中
		ret = write(fd1,buf,count);
		printf("write bytes %d\n",ret);
		// continue read file
		count = read(fd, buf, sizeof(buf));
	}

	//close file
	close(fd);
	close(fd1);
	return 0;
}

posted @ 2022-10-25 17:07  mnst  阅读(29)  评论(0)    收藏  举报