組み込みLINUXドライバーの学習4.キャラクターデバイスドライバーのプログラミング(4)ユーザー空間実装コードのドライバーテスト

組み込みLINUXドライバーの学習4.キャラクターデバイスドライバーのプログラミング(4)ユーザー空間実装コードのドライバーテスト

//编译好之后在下位机执行
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
/* 打印LED灯现在的运行状态(开灯|关灯)*/
void print_led_state(int fd){
    
    
    int ubuf[4];
    int ret_r;
    ret_r = read(fd,ubuf,sizeof(int)*4);
    int i = 0;
    for(; i <4 ; i++){
    
    
        //读取内核空间传递过来的数组内容,0表示开灯,1表示关灯;
        if(ubuf[i] == 0){
    
    
            printf("led%d为开\n",i);
        }
        else{
    
    
            printf("led%d为关\n",i);
        }
    }
}
int main(int argc , char * argv[]){
    
    
    //判断参数数量是否对
    if(argc != 3){
    
    
        printf("参数错误:\n");
        printf("         comm <filename> <on|off>\n");
        return -1;
    }
    int fd;
    fd = open(argv[1],O_RDWR);
   // 打开驱动文件失败的处理方式
    if (fd < 0) {
    
    
        printf("打开文件%s失败    fd : %d\n",argv[1],fd);
        return -1;
    }
    int uindex;
    //根据命令行传递过来的on | off,向内核空间写0或1,即:开关灯操作
    if(strcmp(argv[2],"on") == 0){
    
    
        uindex = 0;
        write(fd,&uindex,4);
       print_led_state(fd); // 打印LED类当前有状态:开灯 | 关灯;
    }
    else if(strcmp(argv[2],"off") ==0){
    
    
        uindex = 1;
        write(fd,&uindex,4);
        print_led_state(fd);
    }
    else {
    
    
    //当不是on | off时,提示参数错误
        printf("参数错误\n");
        close(fd);
        return -1;
    }
    close(fd);//关闭文件
    return 0;
}

おすすめ

転載: blog.csdn.net/weixin_47273317/article/details/107822550