博客专栏

EEPW首页>博客> 嵌入式Linux:fcntl()和ioctl()函数

嵌入式Linux:fcntl()和ioctl()函数

发布人:美男子玩编程 时间:2024-04-26 来源:工程师 发布文章

fcntl()和ioctl()是用于对文件描述符进行控制的两个系统调用,它们在不同的情况下有不同的用途和功能。

#include #include #include  int main() { int fd = open("example.txt", O_RDONLY); if (fd == -1) { perror("open"); return 1; } // 获取文件描述符标志 int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { perror("fcntl"); close(fd); return 1; } // 设置文件描述符标志,添加非阻塞标志 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { perror("fcntl"); close(fd); return 1; } // 其他操作... close(fd); return 0;}

2


ioctl()函数

ioctl()函数可视为文件IO操作的多功能工具箱,可处理各种杂项且不统一的任务,通常用于与特文件或硬件外设交互。

本篇博文只是介绍此系统调用,具体用法将在进阶篇中详细探讨,例如可以利用ioctl获取LCD相关信息等。ioctl()函数原型如下所示(可通过"man 2 ioctl"命令查看):

#include int ioctl(int fd, unsigned long request, ...);


函数ioctl()参数和返回值含义如下:

  • fd:文件描述符。

  • request:用于指定要执行的操作,具体值与操作对象有关,后续会详细介绍。

  • ...:可变参数列表,根据 request 参数确定具体参数,用于与请求相关的操作。

  • 返回值:成功时返回 0,失败时返回 -1。

示例用法:

#include #include #include #include #include  int main() { int fd = open("/dev/sda", O_RDONLY); if (fd == -1) { perror("open"); return 1; } // 查询设备块大小 long block_size; if (ioctl(fd, BLKSSZGET, &block_size) == -1) { perror("ioctl"); close(fd); return 1; } printf("Block size: %ld bytesn", block_size); // 其他操作... close(fd); return 0;}


*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。



关键词:嵌入式Linux

相关推荐

技术专区

关闭