博客專欄

EEPW首頁 > 博客 > 嵌入式Linux:fcntl()和ioctl()函數(shù)

嵌入式Linux:fcntl()和ioctl()函數(shù)

發(fā)布人:美男子玩編程 時(shí)間:2024-04-26 來源:工程師 發(fā)布文章

fcntl()和ioctl()是用于對文件描述符進(jìn)行控制的兩個(gè)系統(tǒng)調(diào)用,它們在不同的情況下有不同的用途和功能。

#include <fcntl.h>#include <stdio.h>#include <unistd.h> int main() {    int fd = open("example.txt", O_RDONLY);    if (fd == -1) {        perror("open");        return 1;    }     // 獲取文件描述符標(biāo)志    int flags = fcntl(fd, F_GETFL, 0);    if (flags == -1) {        perror("fcntl");        close(fd);        return 1;    }     // 設(shè)置文件描述符標(biāo)志,添加非阻塞標(biāo)志    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {        perror("fcntl");        close(fd);        return 1;    }     // 其他操作...     close(fd);    return 0;}

2


ioctl()函數(shù)

ioctl()函數(shù)可視為文件IO操作的多功能工具箱,可處理各種雜項(xiàng)且不統(tǒng)一的任務(wù),通常用于與特文件或硬件外設(shè)交互。

本篇博文只是介紹此系統(tǒng)調(diào)用,具體用法將在進(jìn)階篇中詳細(xì)探討,例如可以利用ioctl獲取LCD相關(guān)信息等。ioctl()函數(shù)原型如下所示(可通過"man 2 ioctl"命令查看):

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


函數(shù)ioctl()參數(shù)和返回值含義如下:

  • fd:文件描述符。

  • request:用于指定要執(zhí)行的操作,具體值與操作對象有關(guān),后續(xù)會(huì)詳細(xì)介紹。

  • ...:可變參數(shù)列表,根據(jù) request 參數(shù)確定具體參數(shù),用于與請求相關(guān)的操作。

  • 返回值:成功時(shí)返回 0,失敗時(shí)返回 -1。

示例用法:

#include <sys/ioctl.h>#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include <linux/fs.h> int main() {    int fd = open("/dev/sda", O_RDONLY);    if (fd == -1) {        perror("open");        return 1;    }     // 查詢設(shè)備塊大小    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;}


*博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請聯(lián)系工作人員刪除。



關(guān)鍵詞: 嵌入式 Linux

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉