crozone
Posts: 12
Joined: Mon Jul 30, 2012 11:27 am

Apparent permissions race condition in /sys/class/gpio

Tue Feb 27, 2018 1:02 am

I am consistently running into a "Permission Denied" error when exporting pins and then immediately attempting to access the files within the pin's "/sys/class/gpio/gpioXX/" folder.

This issue occurs on Raspian image "Linux xxx 4.9.41-v7+ #1023 SMP Tue Aug 8 16:00:15 BST 2017 armv7l GNU/Linux
" on a Raspberry Pi 3.

I have a program running under a non-root user that is part of the "gpio" group. The program exports a pin by writing (for example, '5') to "/sys/class/gpio/export", and then waits for that write to flush. It then attempts to write to the "/sys/class/gpio/gpio5/direction" file. If the program waits an additional second before writing to the direction file, it gets no error and the program functions as it should. If the program doesn't delay, it instead gets a "Permission Denied" error. If the program runs under root, it always succeeds, regardless of whether there's a delay or not.

Given the issue is very reproducible, and the issue does not occur under root, I believe it is a race condition within the file system level permissions on the gpio files, rather than an issue with the files/gpio driver itself not being ready in time. My working theory is that after a gpio export, there is a brief moment where the gpio folder and control files exist, but have an owner of "root:root" before being set to "root:gpio" by something. If the program accesses any files before the new permissions kick in, it gets an error.

Does anyone else have experience with this bug, and does anyone know the mechanism by which the "/sys/class/gpio/*" files are set to owner "root:gpio"? It doesn't appear to be standard kernel behavior, as other non-pi Linux distributions do not seem to do that for you.

Return to “Troubleshooting”