Linux dev_attr 設備文件操作

1. 寫法A:

static ssize_t xxx_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
	return sprintf(buf,"show something\n");
}

static ssize_t xxx_store(struct device *dev,
        struct device_attribute *attr, const char *buf,
        size_t count)
{
#if 1 //字符串判斷
	char on = *buf;
	if(on == '0'){
		printk("to do something A\n");
	}
	if(on == '1'){
		printk("to do something B\n");
	}
#else //字符轉int 判斷
    unsigned long value;
    int ret;
    ret = strict_strtoul(buf,10,&value)
    if(ret){
        return ret;
    }
    switch((int)value){
        case 0:
            printk("to do something A\n");
            break;
        case 1:
            printk("to do something B\n");
            break;
        case 2:
            printk("to do something C\n");
            break;
        default:
            printk("inval param.")
    }
#endif
	return count;
}

static struct device_attribute xxx_dev_attr = {
    .attr = {
    .name = "xxx_state",
	.mode = S_IRWXU|S_IRWXG|S_IRWXO,
    },
    .show = xxx_show,
    .store = xxx_store,
};

static int xxx_probe(struct platform_device *pdev)
{
    int ret = 0;
    ...

    //創建設備操控文件節點
    ret = device_create_file(&(pdev->dev), &xxx_dev_attr);
	if (ret) {
		printk("[xxx_probe] sys file creation failed\n");
	}
}

static int xxx_remove(struct platform_device *pdev)
{
    ...
    device_remove_file(&pdev->dev,&xxx_dev_attr);
	return 0;
}

2. 寫法B:

static ssize_t xxx_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
	return sprintf(buf,"show something\n");
}

static ssize_t xxx_store(struct device *dev,
        struct device_attribute *attr, const char *buf,
        size_t count)
{
#if 1 //字符串判斷
	char on = *buf;
	if(on == '0'){
		printk("to do something A\n");
	}
	if(on == '1'){
		printk("to do something B\n");
	}
#else //字符轉int 判斷
    unsigned long value;
    int ret;
    ret = strict_strtoul(buf,10,&value)
    if(ret){
        return ret;
    }
    switch((int)value){
        case 0:
            printk("to do something A\n");
            break;
        case 1:
            printk("to do something B\n");
            break;
        case 2:
            printk("to do something C\n");
            break;
        default:
            printk("inval param.")
    }
#endif
	return count;
}

//DEVICE_ATTR聲明
static DEVICE_ATTR(xxx_state,S_IRWXU|S_IRWXG|S_IRWXO,xxx_show,xxx_store);

static int xxx_probe(struct platform_device *pdev)
{
    int ret = 0;
    ...

    //創建設備操控文件節點
    ret = device_create_file(&(pdev->dev), &dev_attr_xxx_state);
	if (ret) {
		printk("[xxx_probe] sys file creation failed\n");
	}
}

static int xxx_remove(struct platform_device *pdev)
{
    ...
    device_remove_file(&pdev->dev,&dev_attr_xxx_state);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章