如何在sysfs中访问信息

来自百问网嵌入式Linux wiki

Article purpose

This article provides some information about the sysfs pseudo filesystem usage from the user space.

Sysfs (/sys) pseudo filesystem

Sysfs provides a mean to export kernel data structures, their attributes, and the linkages between them to the user space.

Please refer to sysfs part of 伪文件系统 page.

Sysfs usage

Linux kernel provides a documentation[1] about the rules for sysfs usage.

Some examples are also described below with two different approaches for using sysfs entries from the user space:

  • Linux application in C language
  • bash script.

Example from Linux application

The below example is a typical sequence for using sysfs entry (here a PWM component):

  • open a file descriptor of the sysfs entry file
10  len=snprintf(buf, sizeof(buf), "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle", pwm_channel);
11  fd = open(buf, O_RDWR);
  • if fd is correctly opened, write/read value in the file: pay attention to the "text" format
12  if (fd < 0)
13  {
14      perror("pwm/duty_cycle");
15      return fd;
16  }
  • read: store data to buffer
18  read(fd, buf, sizeof(buf));
  • write: write data from buffer
20  len = snprintf(buf, sizeof(buf), "%d", 900000);
21  write(fd, buf, len);
  • close file descriptor
30  close(fd);

Example for shell command / bash script

Operations on sysfs entries can be done by using command lines (i.e. echo for writing, cat for reading).

In this way, it is possible to use a bash script to execute a configuration sequence, similarly to what a user would do by typing multiple shell commands.

An example is provided in How_to_use_PWM_with_sysfs_interface.

References

<securetransclude src="ProtectedTemplate:PublicationRequestId" params="10265 | 2019-01-16 | BrunoB"></securetransclude>