Linux的运行空间:
Linux的运行空间:内核空间+用户空间
内核空间——存放的是整个内核代码和所有内核模块,以及内核所维护的数据。 用户空间——用户程序的代码和数据。
操作系统提供给用户程序调用系统服务(硬件设备)的一组"特殊"接口。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qZHi7gvy-1654739388114)(https://zyximagestorage.oss-cn-beijing.aliyuncs.com/blogimages/image-20220608184404431.png)]
系统调用可被看成是一个内核与用户空间程序交互的接口——它好比一个信使,把用户进程的请求传达给内核,待内核把请求处理完毕后再将处理结果送回给用户空间。
与具体的硬件完全隔离,用户不需要面向具体的硬件编码,降低了开发的复杂度和难度。
将用户进程隔离,实现内核"保护",用户进程不允许访问内核数据,也无法使用内核函数。用户访问内核的路径是事先规定好的,只能从规定位置进入内核,而不允许肆意跳入内核。有了这样的内核访问路径限制,才能保证内核安全无误。
对于不同平台不同硬件来说。
通过软件中断实现。 **软件中断:**它是通过软件指令触发的中断。Linux系统内核响应软件中断,从用户态切换到内核态,执行相应的系统调用。
系统调用控制程序执行软件中断的过程如下:
系统调用号:
每个系统调用被赋予一个系统调用号,与具体的系统调用相关联。
系统调用表:
内核维护系统调用表,保存系统调用函数的起始位置,系统调用号对应该系统调用在调用表中的偏移量。
还有系统中断。
Glibc实现操作系统提供的系统服务,即为系统调用的封装。
**示例:**更改文件权限
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
int main(void) {
int rc = chmod("./test.txt",S_IWUSR | S_IWGRP | S_IWOTH);
if (rc == -1) {
fprintf(stderr,"chmod failed,errno=%d\n",errno);
} else {
printf("chmod success!\n");
}
return 0;
}
函数原型:
long int syscall(long int sysno,...);
传参说明:
**示例:**更改文件权限
#include <sys/syscall.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
int main(void) {
int rc = syscall(SYS_chmod, "./test.txt", S_IROTH | S_IRGRP | S_IRUSR);
if (rc == -1) {
fprintf(stderr,"chmod failed,errno=%d\n",errno);
} else {
printf("chmod success!\n");
}
return 0;
}
系统调用的次数会影响程序的执行效率。
**示例:**调用write往文件里写数据,更改每次写的大小进行对比。
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
//宏是直接替换,注意括号
#define TOTAL_SIZE (1024*1024*500)
#define BUF_SIZE 4096
int main(int argc,char**argv) {
char buffer[BUF_SIZE];
const char* filename = "./write.txt";
int fd = -1;
int i = 0;
memset(buffer, '8', BUF_SIZE);
fd = open(filename, O_RDWR | O_TRUNC | O_CREAT);
if (fd < 0) {
fprintf(stderr,"fopen failed,reason:%s.\n exit\n",strerror(errno));
return -1;
}
int num = TOTAL_SIZE / BUF_SIZE;
for (i = 0; i < num; i++) {
if (write(fd, buffer, BUF_SIZE) < 0) {
fprintf(stderr,"write failed!reason:%s.\n",strerror(errno));
}
}
close(fd);
return 0;
}
将 BUF_SIZE 更改为 16后,每次写的量减少了,增加了系统调用的次数。
**两次时间对比:**1-4096,2-16。
罪魁祸首-用户态和内核态的切换
一多一少解决效率问题: