Linux 文件操作系统函数

系统函数:
调用系统函数,用户空间 -> 内核空间

系统API:
应用层:fopen
系统层:open
内核:设备驱动函数

FILE *fp.
fp 为一个结构体的指针,结构体中包含打开文件的各种属性。

打开文件 --> 写入IO缓冲区 --> 磁盘

虚拟地址空间:
程序运行起来后,磁盘上都会有一个虚拟地址空间,在数据处理的时候会通过MMU(内存管理机制)把虚拟地址空间映射到物理内存上进行处理。
在这里插入图片描述
进程管理:
PCB(一个400多行的结构体)进程管理控制块中的文件描述符标,文件描述符表前三个默认打开stdin stdout stderr.
在这里插入图片描述fork函数理解:
子进程被创建后,父子进程的执行顺序是CPU自己调度的。

  在fork后shell终端是不知道创建了一个子进程,如果当父进程先于子进程执行结束,shell发现进程结束会直接从后台切换到前台运行,这时子进程数据输出就会错乱。

在这里插入图片描述
在这里插入图片描述

如上图,fork后,子进程会完全拷贝一份父进程,但它只会从fork处接着往下执行

读时共享,写时复制:
建立全局变量是不可以实现进程间通信的,如下图理解。
在这里插入图片描述

man man ==》可以查看函数手册位于man的第几章

open()
注意:
创建文件时,文件权限为:mode & ~umask,man中有详细描述,详见手册。

write()
read()
off_t lseek(int fd, off_t offset, int whence); //移动文件指针
whence:
SEEK_SET
SEEK_CUR
SEEK_END
lseek(fd, 0, SEEK_SET); //文件指针移动到文件头,返回值为0
lseek(fd, 0, SEEK_CUR);// 返回文件指针的当前位置
lseek(fd, 0, SEEK_END);//文件指针移到文件尾,返回文件大小

lseek文件拓展:
lseek(fd, 1000, SEEK_END);//在原文件大小的基础上再增加1000byte。
write(fd,“a”, 1); //要最后再写入一个字符才能拓展成功。

/*********************写操作****************************/
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
 	int file_handle;
 	ssize_t write_num;
 	char ch[] = "These red roses are for you!";
	file_handle = open("./hell.txt", O_WRONLY);
	if(file_handle < 0)
	{
  		printf("open:%s", strerror(errno));
  		return file_handle;
 	}
	write_num = write(file_handle, ch, strlen(ch));
 	if(write_num < 0)
 	{
  		printf("write:%s", strerror(errno));
  		return file_handle;
 	}
	if(0 > close(file_handle))
 	{
  		printf("close:%s", strerror(errno));
 	}
 	else
 	{
  		printf("success\n");
 	}
}
/*******************************************************************/

****************************读文件操作***********************************/

#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  int file_handle;
  ssize_t read_num;
  int count = 0;
  char prin[1024] = "0";
  char ch[8];
 file_handle = open("./hell.txt", O_RDONLY);
 if(file_handle < 0)
 {
    printf("open:%s", strerror(errno));
    return file_handle;
  }
  while(1)
  {
  	read_num = read(file_handle, ch, sizeof(ch));
  	if(read_num < 0)
 	{
  		printf("read:%s", strerror(errno));	//perror(“open”)
   		return file_handle;
  	}
  	if(read_num == 0)
  	{
   		break;
  	}
  }
 if(0 > close(file_handle))
  {
    printf("close:%s", strerror(errno));	//perror("close")
  }
  else
  {
    printf("success\n");
  }
}
printf("data:%s\n", prin);
/**********************************************************/

猜你喜欢

转载自blog.csdn.net/weixin_42411048/article/details/106599938