-- TOC --
测试ioctl系统调用,同时测试mychar驱动。
$ cat try_ioctl.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <assert.h>
#include "mychar.h"
#define ERRBUF_SIZE 32
#define _PERROR \
do { \
char errbuf[ERRBUF_SIZE] = {0}; \
sprintf(errbuf, "%s:%d", __FILE__, __LINE__); \
perror(errbuf); \
} while(0) \
int main(int argc, char **argv) {
int fd;
unsigned long rtv;
assert(argc == 2);
if ((fd=open(argv[1],O_RDONLY)) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 1024);
ioctl(fd, MYCHAR_IOC_RESET);
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 4096);
if (ioctl(fd, MYCHAR_IOC_QUERY, &rtv) == -1) {
_PERROR;
return errno;
}
assert(rtv == 4096);
rtv = 1234;
if (ioctl(fd, MYCHAR_IOC_SET, &rtv) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 1234);
rtv = 2345;
if (ioctl(fd, MYCHAR_IOC_QNS, &rtv) == -1) {
_PERROR;
return errno;
}
assert(rtv == 1234);
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 2345);
if (ioctl(fd, MYCHAR_IOC_CLS) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 0);
rtv = 1234;
if (ioctl(fd, MYCHAR_IOC_SET, &rtv) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 1234);
rtv = 2345;
if (ioctl(fd, MYCHAR_IOC_CNS, &rtv) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 2345);
rtv = 1024;
if (ioctl(fd, MYCHAR_IOC_SET, &rtv) == -1) {
_PERROR;
return errno;
}
assert(ioctl(fd, MYCHAR_IOC_QUERY2) == 1024);
printf("all ioctl success!\n");
return 0;
}
就是一顿ioctl操作,测试OK
$ gcc -Wall -Wextra -I/home/xinlin/sources/linux-5.14.14/include try_ioctl.c -o try_ioctl
$ ./try_ioctl mychar-5
all ioctl success!
$ ./try_ioctl mychar-5
all ioctl success!
注意:ioctl接口的返回是int类型,在设计使用return的方式返回值的时候,注意类型!
本文链接:https://cs.pynote.net/sf/linux/dd/202201071/
-- EOF --
-- MORE --