系统调用&文件描述

一、系统调用

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、文件描述符引用图解

相关推荐
程序员小崔日记2 小时前
20块钱注册一年 .COM 域名!Spaceship 最新优惠教程,支付宝即可付款(附优惠码)
服务器·腾讯云·域名
Better Bench2 小时前
WSL2 Ubuntu 中 Claude CLI “command not found” 故障排查与修复
linux·ubuntu·claude·wsl·claudecode
实心儿儿3 小时前
Linux —— 进程间关系和守护进程
linux·运维·服务器
FII工业富联科技服务3 小时前
工业设备运维如何Agentic化?拆解Factory Brain的设备运维架构
大数据·运维·人工智能·架构·制造
林浅不想努力3 小时前
LVS知识点总结
服务器·云原生·lvs
Dawn-bit4 小时前
Linux磁盘管理详解
linux·运维·服务器·计算机网络·云计算
RisunJan5 小时前
Linux命令-sftp(SSH 文件传输协议客户端)
linux·运维
极客先躯6 小时前
高级java每日一道面试题-2026年05月03日-实战篇[Docker]-如何实现容器化环境的数据加密?
java·运维·docker·容器·金融·加解密·高级面试
龙仔7257 小时前
人大金仓OS_Core数据库自动备份实施笔记(银河麒麟Linux)
linux·数据库·笔记·备份·人大金仓
老杨聊技术7 小时前
CentOS 7 安装 MySQL 8 保姆级教程
linux·mysql·centos