1

On the device I'm working on, I can write to /sys/class/leds to turn a led light on/off. Can I keep the file open in my code and only close when the process exits, or should I only open the file when I need to write to it?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
mr49
  • 1,053
  • 1
  • 8
  • 26

3 Answers3

1

Yes. There seems to be no harm in doing so.

I tried the following in first shell

#tailf /sys/class/leds/mmc0\:\:/brightness

And in second shell, tried the same thing.

#tailf /sys/class/leds/mmc0\:\:/brightness

This experiment is just to show that, at no point opening(tailf) from another process(second shell) was affected by a previous open(tailf) in the first shell.

Drad
  • 96
  • 1
  • 3
  • Just keep one file open for a longer time (`tail -f`). – CL. Mar 08 '16 at 12:45
  • @subin I beg to differ from the point that sysfs entry will be cached. sysfs entries are in ram like a ramfs/tmpfs. There is no disk cache like in the case of actual disks. – Drad Mar 09 '16 at 20:12
0

If you look at tools/thermal/tmon/sysfs.c in Linux kernel source, all the functions use an open->read/write->close. Especially when using standard C library functions like fread/fwrite, the buffering can cause problems. Or you can use fflush() after each write. I would still prefer opening and closing it for each write as sysfs entries are not disk based and can change in runtime. Especially if they correspond to hotpluggable devices.

subin
  • 490
  • 3
  • 13
0

It is always best practice to open and close the file descriptor (fopen) every time. If you will always keep your sysfs open; then it will hold that particular amount of memory till the end.

vinod maverick
  • 670
  • 4
  • 14