嵌入式Linux:fcntl()和ioctl()函數(shù)
fcntl()和ioctl()是用于對文件描述符進行控制的兩個系統(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; } // 獲取文件描述符標志 int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { perror("fcntl"); close(fd); return 1; } // 設(shè)置文件描述符標志,添加非阻塞標志 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操作的多功能工具箱,可處理各種雜項且不統(tǒng)一的任務(wù),通常用于與特文件或硬件外設(shè)交互。
本篇博文只是介紹此系統(tǒng)調(diào)用,具體用法將在進階篇中詳細探討,例如可以利用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ù)會詳細介紹。
...:可變參數(shù)列表,根據(jù) request 參數(shù)確定具體參數(shù),用于與請求相關(guān)的操作。
返回值:成功時返回 0,失敗時返回 -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)友個人發(fā)布,僅代表博主個人觀點,如有侵權(quán)請聯(lián)系工作人員刪除。