Accessing the GPIO (of a raspberry pi) without ``sudo``

后端 未结 1 1036
我寻月下人不归
我寻月下人不归 2020-12-24 07:55

This question might not be specific to the raspberry pi, of course. Also, I\'m relatively new to Linux.

I want to write a little library (in node.js, if that matters

相关标签:
1条回答
  • 2020-12-24 08:26

    Rakesh, I've just been trying to figure out exactly the same thing, and I think I've solved it.

    You don't need to understand much of the makefile at all. The important lines are the following, which are executed in bash when you run sudo make install

    install: install-files
        groupadd -f --system gpio
        chgrp gpio $(DESTDIR)/bin/gpio-admin
        chmod u=rwxs,g=rx,o= $(DESTDIR)/bin/gpio-admin
    

    groupadd -f --system gpio creates a system group called gpio. chgrp gpio $(DESTDIR)/bin/gpio-admin changes the group of the binary (which the C file gpio-admin.c was compiled to) to gpio. The owner of the binary is still root (since you're running make as root.) chmod u=rwxs,g=rx,o= $(DESTDIR)/bin/gpio-admin does two important things. Firstly, it lets a member of the gpio group run gpio-admin. Secondly, it sets the setuid bit on gpio-admin.

    When you add yourself to the gpio group, you can run gpio-admin, without using sudo, but gpio admin will act like it is being run under sudo. This allows it to write to the /sys/class/gpio/export file. It also allows it to change the owner of the files /sys/class/gpio/gpio[pin number]/direction etc. that get created.

    Even if you change the group of /sys/class/gpio/export to gpio, and set permissions to allow you to write to it

    sudo chgrp gpio /sys/class/gpio/export /sys/class/gpio/unexport
    sudo chmod g+rwx /sys/class/gpio/export /sys/class/gpio/unexport
    

    you can export a pin without superuser powers

    echo 22 > /sys/class/gpio/export
    

    but the files /sys/class/gpio/gpio22/direction etc. will still be create with root as the owner and group, and you'll need to use sudo to change them. Also, ownership of the export and unexport files will revert to root after each reboot.

    0 讨论(0)
提交回复
热议问题