Linux下的系统编程——系统调用(五)

简介: Linux下的系统编程——系统调用(五)

前言:

操作系统实现并提供给外部应用程序的编程接口。(Application Programming Interface,API)。系统调用就是应用程序同系统之间数据交互的桥梁。

一、open/close函数

1.open函数:

   (1)int open(char *pathname, int flags)    #include

   参数:

       pathname: 欲打开的文件路径名

       flags:文件打开方式:  #include

                O_RDONLY|O_WRONLY|O_RDWR                    O_CREAT|O_APPEND|O_TRUNC|O_EXCL|O_NONBLOCK ....

   返回值:

       成功: 打开文件所得到对应的 文件描述符(整数)

       失败: -1, 设置errno    

语法
open()方法语法格式如下:
 
os.open(file, flags[, mode]);
 
参数
file – 要打开的文件
 
flags – 该参数可以是以下选项,多个使用 “|” 隔开:
 
O_RDONLY: 以只读的方式打开
O_WRONLY: 以只写的方式打开
O_RDWR : 以读写的方式打开
O_NONBLOCK: 打开时不阻塞
O_APPEND: 以追加的方式打开
O_CREAT: 创建并打开一个新文件
O_TRUNC: 打开一个文件并截断它的长度为零(必须有写权限)
O_EXCL: 如果指定的文件存在,返回错误
O_SHLOCK: 自动获取共享锁
O_EXLOCK: 自动获取独立锁
O_DIRECT: 消除或减少缓存效果
O_FSYNC : 同步写入
O_NOFOLLOW: 不追踪软链接
 
 
 
1)PROT_READ:表示内存段内的内容可写;
 
2)PROT_WRITE:表示内存段内的内容可读;
 
3)PROT_EXEC:表示内存段中的内容可执行;
 
4)PROT_NONE:表示内存段中的内容根本没法访问。

   (2)int open(char *pathname, int flags, mode_t mode)        123  775    

   参数:

       pathname: 欲打开的文件路径名

       flags:文件打开方式:    

              O_RDONLY|O_WRONLY|O_RDWR                    O_CREAT|O_APPEND|O_TRUNC|O_EXCL|O_NONBLOCK ....

       mode: 参数3使用的前提, 参2指定了 O_CREAT。    

               取值8进制数,用来描述文件的 访问权限。 rwx    0664

               创建文件最终权限 = mode & ~umask

   返回值:

       成功: 打开文件所得到对应的 文件描述符(整数)

       失败: -1, 设置errno    

2.close函数:

   int close(int fd);

3.错误处理函数:        

   与 errno 相关。

       printf("xxx error: %d\n", errno);

 

char *strerror(int errnum);
        printf("xxx error: %s\n", strerror(errno));

 

void perror(const char *s);
        perror("open error");

二、read/write函数:

1.read函数:

   ssize_t read(int fd, void *buf, size_t count);

   参数:

       fd:      文件描述符

       buf:    存数据的缓冲区

       count:缓冲区大小

   返回值:

       0:          读到文件末尾。

       成功;    > 0 读到的字节数。

       失败:    -1, 设置 errno

      -1: 并且 errno = EAGIN 或 EWOULDBLOCK, 说明不是read失败,而是read在以非阻塞方式读一个设备文件(网络文件),并且文件无数据。

2.write函数:

   ssize_t write(int fd, const void *buf, size_t count);

   参数:

       fd:     文件描述符

       buf:   待写出数据的缓冲区

       count:数据大小

   返回值:

       成功;    写入的字节数。

       失败:    -1, 设置 errno

示例:

用read和write函数实现cp操作(将open.c文件中的代码复制到open2.c中)

  1 #include <unistd.h>
  2 #include <fcntl.h>
  3 #include <stdlib.h>
  4 #include <pthread.h>
  5 #include <string.h>
  6 #include <stdio.h>
  7 
  8 int main(int argc,char *argv[])
  9 {
 10     char buf[1024];
 11 
 12     int n = 0;
 13 
 14     int fd1 = open(argv[1],O_RDONLY); //read
 15     if(fd1 == -1){
 16         perror("open argv1 error");
 17         exit(1);
 18     }
 19 
 20     int fd2 = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0664);
 21     if(fd2 == -1){
 22         perror("open argv2 error");
 23         exit(1);
 24     }
 25     while((n = read(fd1,buf,1024))!=0){
 26         if(n < 0)
 27         {
 28             perror("read error");
 29             break;
 30         }
 31         write(fd2,buf,n);
 32     }
 33 
 34     close(fd1);
 35     close(fd2);
 36 }
~                       

系统调用和库函数比较

预读入缓输出

三、阻塞、非阻塞

   阻塞、非阻塞:  是设备文件、网络文件的属性。

   产生阻塞的场景: 读设备文件、读网络文件。(读常规文件无阻塞概念。)

   /dev/tty --> 终端文件。

1.阻塞

  1 #include <unistd.h>
  2 #include <stdlib.h>
  3 #include <stdio.h>
  4 
  5 
  6 int main(void)
  7 {
  8     char buf[10];
  9     int n;
 10 
 11     n = read(STDIN_FILENO, buf, 10);   
 12     // #define STDIN_FILENO 0   STDOUT_FILENO 1  STDERR_FILENO 2
 13     if(n < 0){
 14         perror("read STDIN_FILENO");
 15         exit(1);
 16     }
 17     write(STDOUT_FILENO, buf, n);
 18 
 19     return 0;
 20 }   

现在发生阻塞,一直处于读的状态

当我们输入一串字符时,读操作结束,阻塞解除

那么阻塞是谁的特性?是read/write的吗?

答案当然不是了,应该是文件的属性,也就是设备文件或者网络文件

2.改变阻塞特性

open("/dev/tty", O_ RDWR|O_NONBLOCK)    --- 设置 /dev/tty 非阻塞状态。(默认为阻塞状态)

3.非阻塞

  1 #include <unistd.h>
  2 #include <fcntl.h>
  3 #include <errno.h>
  4 #include <stdio.h>
  5 #include <stdlib.h>
  6 #include <string.h>
  7 
  8 int main(void)
  9 {
 10     char buf[10];
 11     int fd, n;
 12 
 13     fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
 14     if (fd < 0) {
 15         perror("open /dev/tty");
 16         exit(1);
 17     }
 18 
 19 tryagain:
 20 
 21     n = read(fd, buf, 10);
 22     if (n < 0) {
 23         if (errno != EAGAIN) {      // if(errno != EWOULDBLOCK)
 24             perror("read /dev/tty");
 25             exit(1);
 26         } else {
 27             write(STDOUT_FILENO, "try again\n", strlen("try again\n"));
 28             sleep(2);
 29             goto tryagain;
 30         }
 31     }
 32 
 33     write(STDOUT_FILENO, buf, n);
 34     close(fd);
 35 
 36     return 0;
 37 }

4.设置非阻塞后的循环停止时间

  1 #include <unistd.h>
  2 #include <fcntl.h>
  3 #include <stdlib.h>
  4 #include <stdio.h>
  5 #include <errno.h>
  6 #include <string.h>
  7 
  8 #define MSG_TRY "try again\n"
  9 #define MSG_TIMEOUT "time out\n"
 10 
 11 int main(void)
 12 {
 13     char buf[10];
 14     int fd, n, i;
 15 
 16     fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
 17     if(fd < 0){
 18         perror("open /dev/tty");
 19         exit(1);
 20     }
 21     printf("open /dev/tty ok... %d\n", fd);
 22 
 23     for (i = 0; i < 5; i++){
 24         n = read(fd, buf, 10);
 25         if (n > 0) {                    //说明读到了东西
 26             break;
 27         }
 28         if (errno != EAGAIN) {          //EWOULDBLOCK  
 29             perror("read /dev/tty");
 30             exit(1);
 31         } else {
 32             write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
 33             sleep(2);
 34         }
 35     }
 36 
 37     if (i == 5) {
 38         write(STDOUT_FILENO, MSG_TIMEOUT, strlen(MSG_TIMEOUT));
 39     } else {
 40         write(STDOUT_FILENO, buf, n);
 41     }
 42 
 43     close(fd);
 44 
 45     return 0;
 46 }
 
 

四、文件描述符:

    PCB进程控制块: 本质是结构体

   成员:文件描述符表

   文件描述符:0/1/2/3/4........../1023    表中可用的最小的。

   0 - STDIN_FILENO

   1 - STDOUT_FILENO

   2 - STDERR_FILENO

五、fcntl函数:

        改变一个【己经打开】的文件的访问控制属性。

       重点掌握两个参数的使用,F_GETFL 和 F_SETFL。

       【fcntl.c】

    int (int fd, int cmd, ...)

   int flgs = fcntl(fd,  F_GETFL);

   flgs |= O_NONBLOCK

   fcntl(fd,  F_SETFL, flgs);

   获取文件状态: F_GETFL

   设置文件状态: F_SETFL

  1 #include <unistd.h>
  2 #include <fcntl.h>
  3 #include <errno.h>
  4 #include <stdio.h>
  5 #include <stdlib.h>
  6 #include <string.h>
  7 
  8 #define MSG_TRY "try again\n"
  9 
 10 int main(void)
 11 {
 12     char buf[10];
 13     int flags, n;
 14 
 15     flags = fcntl(STDIN_FILENO, F_GETFL); //获取stdin属性信息
 16     if(flags == -1){
 17         perror("fcntl error");
 18         exit(1);
 19     }
 20     flags |= O_NONBLOCK;
 21     int ret = fcntl(STDIN_FILENO, F_SETFL, flags);
 22     if(ret == -1){
 23         perror("fcntl error");
 24         exit(1);
 25     }
 26 
 27 tryagain:
 28     n = read(STDIN_FILENO, buf, 10);
 29     if(n < 0){
 30         if(errno != EAGAIN){
 31             perror("read /dev/tty");
 32             exit(1);
 33         }
 34         sleep(3);
 35         write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
 36         goto tryagain;
 37     }
 38     write(STDOUT_FILENO, buf, n);
 39 
 40     return 0;
 41 }

六、lseek函数:

lseek函数:

   off_t lseek(int fd, off_t offset, int whence);

   参数:

       fd:         文件描述符

       offset:   偏移量

       whence:起始偏移位置: SEEK_SET/SEEK_CUR/SEEK_END

   返回值:

       成功:较起始位置偏移量

       失败:-1 errno

   应用场景:    

       1. 文件的“读”、“写”使用同一偏移位置

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
 
int main(void)
{
  int fd, n;
  char msg[] = "It's a test for lseek\n";
  char ch;
 
  fd = open("lseek.txt", O_RDWR|O_CREAT, 0644);
  if(fd < 0){
    perror("open lseek.txt error");
    exit(1);
  }
 
  write(fd, msg, strlen(msg));   
  //使用fd对打开的文件进行写操作,问价读写位置位于文件结尾处。
 
  lseek(fd, 0, SEEK_SET);        
  //修改文件读写指针位置,位于文件开头。 注释该行会怎样呢?
 
  while((n = read(fd, &ch, 1))){
    if(n < 0){
      perror("read error");
      exit(1);
    }
    write(STDOUT_FILENO, &ch, n);   
    //将文件内容按字节读出,写出到屏幕
  }
 
  close(fd);
 
  return 0;
}

2. 使用lseek获取文件大小

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
 
int main(int argc,char *argv[])
{
  int fd;
 
  fd = open(argv[1],O_RDWR);
  if(fd < -1){
    perror("open lseek.txt error");
    exit(1);
  }
 
  int len = lseek(fd, 0, SEEK_END);
  if(len == -1){
    perror("lseek error");
    exit(1);
  }
  printf("len of msg = %d\n", len);
 
  close(fd);
 
  return 0;
}

3. 使用lseek拓展文件大小:要想使文件大小真正拓展,必须引起IO操作。

   使用 truncate 函数,直接拓展文件。   int ret = truncate("dict.cp", 250);

(1)扩展文件大小:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
 
int main(int argc,char *argv[])
{
  int fd;
 
  fd = open(argv[1],O_RDWR);
  if(fd < -1){
    perror("open lseek.txt error");
    exit(1);
  }
 
  int len = lseek(fd, 111, SEEK_END);
  if(len == -1){
    perror("lseek error");
    exit(1);
  }
  printf("len of msg = %d\n", len);
 
  close(fd);
 
  return 0;
}

(2)扩展文件大小—引起IO操作:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
 
int main(void)
{
    int fd;
    char buf[64];
    int ret = 0;
 
    fd = open("./file.txt", O_RDONLY);
    if (fd == -1) {
        printf("open file error\n");
        exit(1);
    }
    printf("---open ok---\n");
 
    while((ret = read(fd, buf, sizeof(buf)))) {
        write(1, buf, ret);
    }
 
    close(fd);
 
    return 0;
}

使用 truncate 函数,直接拓展文件

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
 
int main(int argc,char *argv[])
{
  
  int ret = truncate("test.c",250);
 
  printf("ret = %d\n",ret);
 
 
  return 0;
}

七、传入传出参数:

1.传入参数:

   1. 指针作为函数参数。

   2. 通常有const关键字修饰。

   3. 指针指向有效区域, 在函数内部做读操作。

2.传出参数:

   1. 指针作为函数参数。

   2. 在函数调用之前,指针指向的空间可以无意义,但必须有效。

   3. 在函数内部,做写操作。

   4。函数调用结束后,充当函数返回值。

3.传入传出参数:

   1. 指针作为函数参数。

   2. 在函数调用之前,指针指向的空间有实际意义。

   3. 在函数内部,先做读操作,后做写操作。

   4. 函数调用结束后,充当函数返回值。

目录
相关文章
|
7月前
|
Ubuntu Linux Anolis
Linux系统禁用swap
本文介绍了在新版本Linux系统(如Ubuntu 20.04+、CentOS Stream、openEuler等)中禁用swap的两种方法。传统通过注释/etc/fstab中swap行的方式已失效,现需使用systemd管理swap.target服务或在/etc/fstab中添加noauto参数实现禁用。方法1通过屏蔽swap.target适用于新版系统,方法2通过修改fstab挂载选项更通用,兼容所有系统。
683 3
Linux系统禁用swap
|
7月前
|
Linux
Linux系统修改网卡名为eth0、eth1
在Linux系统中,可通过修改GRUB配置和创建Udev规则或使用systemd链接文件,将网卡名改为`eth0`、`eth1`等传统命名方式,适用于多种发行版并支持多网卡配置。
1233 3
|
Ubuntu Linux 网络安全
Linux系统初始化脚本
一款支持Rocky、CentOS、Ubuntu、Debian、openEuler等主流Linux发行版的系统初始化Shell脚本,涵盖网络配置、主机名设置、镜像源更换、安全加固等多项功能,适配单/双网卡环境,支持UEFI引导,提供多版本下载与持续更新。
766 3
Linux系统初始化脚本
|
8月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
597 18
|
7月前
|
安全 Linux Shell
Linux系统提权方式全面总结:从基础到高级攻防技术
本文全面总结Linux系统提权技术,涵盖权限体系、配置错误、漏洞利用、密码攻击等方法,帮助安全研究人员掌握攻防技术,提升系统防护能力。
921 1
|
7月前
|
监控 安全 Linux
Linux系统提权之计划任务(Cron Jobs)提权
在Linux系统中,计划任务(Cron Jobs)常用于定时执行脚本或命令。若配置不当,攻击者可利用其提权至root权限。常见漏洞包括可写的Cron脚本、目录、通配符注入及PATH变量劫持。攻击者通过修改脚本、创建恶意任务或注入命令实现提权。系统管理员应遵循最小权限原则、使用绝对路径、避免通配符、设置安全PATH并定期审计,以防范此类攻击。
1285 1
|
8月前
|
缓存 监控 Linux
Linux系统清理缓存(buff/cache)的有效方法。
总结而言,在大多数情形下你不必担心Linux中buffer与cache占用过多内存在影响到其他程序运行;因为当程序请求更多内存在没有足够可用资源时,Linux会自行调整其占有量。只有当你明确知道当前环境与需求并希望立即回收这部分资源给即将运行重负载任务之前才考虑上述方法去主动干预。
2270 10
|
8月前
|
安全 Linux 数据安全/隐私保护
为Linux系统的普通账户授予sudo访问权限的过程
完成上述步骤后,你提升的用户就能够使用 `sudo`命令来执行管理员级别的操作,而无需切换到root用户。这是一种更加安全和便捷的权限管理方式,因为它能够留下完整的权限使用记录,并以最小权限的方式工作。需要注意的是,随意授予sudo权限可能会使系统暴露在风险之中,尤其是在用户不了解其所执行命令可能带来的后果的情况下。所以在配置sudo权限时,必须谨慎行事。
1531 0
|
8月前
|
Ubuntu Linux 开发者
国产 Linux 发行版再添新成员,CutefishOS 系统简单体验
当然,系统生态构建过程并不简单,不过为了帮助国产操作系统优化生态圈,部分企业也开始用国产操作系统替代 Windows,我们相信肯定会有越来越多的精品软件登录 Linux 平台。
720 0
|
8月前
|
Ubuntu 安全 Linux
Linux系统入门指南:从零开始学习Linux
Shell脚本是一种强大的自动化工具,可以帮助您简化重复的任务或创建复杂的脚本程序。了解Shell脚本的基本语法和常用命令,以及编写和运行Shell脚本的步骤,将使您更高效地处理日常任务。
706 0