The kernel reads and writes files in sysfs.

Source: Internet
Author: User

The kernel reads and writes files in sysfs.

Recently, when implementing a new feature in Android, you need to read data from a file in sysfs in the driver and save it to another file after computation.
Reading and Writing files in kernel and reading files in userspace require calling different interfaces.

Global variables:

#define FILE_PATH "/data/xxxx.cfg"#define BUF_SIZE 128char global_buf[BUF_SIZE];struct file *fp;

Read functions:

static int get_data_from_sysfs(const char *path, char *buf){    mm_segment_t fs;    fp = filp_open(path, O_RDONLY, 0644);    if (unlikely(IS_ERR(fp))) {        pr_info("Fail to open file \"%s\"\n", path);        return -1;    }    fp->f_pos = 0;    fs = get_fs();    set_fs(KERNEL_DS);    fp->f_op->read(fp, buf, BUF_SIZE, &(fp->f_pos));    set_fs(fs);    filp_close(fp, NULL);    return 0;}

Write Functions

static int update_data_to_sysfs(void){    mm_segment_t fs;    sprintf(global_buf, "%u    %u    %u\n", aaa,            bbb, ccc);    fp = filp_open(FILE_PATH, O_RDWR | O_CREAT, 0644);    fp->f_pos = 0;    fs = get_fs();    set_fs(KERNEL_DS);    fp->f_op->write(fp, global_buf, sizeof(global_buf), &fp->f_pos);    set_fs(fs);    return 0;}

In the function prototype, the second parameter of fp-> f_op-> write and fp-> f_op-> read is the data in userspace. Therefore, it must be converted to the kernel state available, after the call is complete, it is converted back to the user State.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.