系统调用&文件描述

一、系统调用

1、open打开文件

cpp 复制代码
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main()
{
    /*
    const char *__file 打开文件的路径
    int __oflag 打开文件的模式
    【1】O_RDONLY 只读模式
    【2】O_WRONLY 只写模式
    【3】O_RDWR 读写模式
    【4】O_CREAT 如果不存在创建文件
    【5】O_APPEND 追加写模式
    【6】O_TRUNC 截断文件长度为0
    ...可变参数:O_CREAT 创建文件的权限 0664
    return:文件描述符 如果打开文件失败返回-1 同时设置全局变量errno表示对应的错误
    int open(const char *__file, int __oflag, ...)
    */
    int fd=open("io1.txt",O_RDONLY | O_CREAT,0664);
    if (fd==-1)
    {
        printf("打开文件失败\n");
    }
    
    return 0;
}

MakeFile

cpp 复制代码
unistd_test:unistd_test.c
	-$(CC) -o $@ $^ 
	-./$@
	-rm ./$@

2、read

3、write

4、close

5、exit

6、练习

读取io.txt文件内容

cpp 复制代码
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>

int main()
{
    //打开文件
    int fd = open("io.txt",O_RDONLY);
    if (fd == -1)
    {
        perror("open");
        exit(EXIT_FAILURE);
    }

    char *buf[1024];
    ssize_t bytes_read;
    bytes_read=read(fd,buf,sizeof(buf));
    if (bytes_read == -1)
    {
        perror("read");
        close(fd);
        exit(EXIT_FAILURE);
    }
    ssize_t bytes_write;
    while (bytes_read > 0)
    {
        bytes_write=write(STDOUT_FILENO,buf,bytes_read);
        bytes_read=read(fd,buf,sizeof(buf));
    }
    
    if (bytes_write == -1)
    {
        perror("write");
        close(fd);
        exit(EXIT_FAILURE);
    }
    close(fd);


    return 0;
}

Makefile

cpp 复制代码
system_call_test:system_call_test.c
	-$(CC) -o $@ $^
	-./$@
	-rm ./$@

二、文件描述符

1、定义

2、struct file

3、struct path

4、struct inode

5、文件描述符表关联的数据结构

6、文件描述符引用图解

相关推荐
都在酒里21 分钟前
Linux字符设备驱动开发(十):综合实例——I2C传感器 + LED智能控制与进阶指南
linux·运维·服务器·驱动开发·交互
2301_809051148 小时前
Linux 网络编程 学习笔记
linux·网络·学习
wanhengidc8 小时前
服务器租用有何优点
运维·服务器·安全·web安全
ZGi.ai8 小时前
人工审查节点:让自动化工作流多一步人工把关
运维·人工智能·自动化·人机协同·智能体工作流·人工审查
坤昱8 小时前
cfs调度类深入解刨——最新内核细节分析2
linux·服务器·cfs·cfs调度·eevdf调度·eevdf·kernel 7.1
艾莉丝努力练剑8 小时前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
海市公约8 小时前
Linux核心基础命令与权限管理实战指南
linux·运维·服务器·vim·权限管理·系统监控·命令行
eggcode8 小时前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
wkd_0079 小时前
Ubuntu 22.04 Samba 连接故障排查记:从“用户名或密码错误”到 NTLM 版本不兼容
linux·运维·ubuntu
企服AI产品测评局9 小时前
Agent适配信创环境实测:企业级自动化如何实现国产操作系统与数据库全兼容?
运维·数据库·人工智能·ai·chatgpt·自动化