Note that a normal user by default on Raspbian cannot do this:
echo "17" > /sys/class/gpio/unexport
Or, conversely, use
export, even if they are a member of the
gpio group. This points to the fact that as the OP admits in another thread, there might have been some tweaks made, possibly by other software that was installed. However, it is probably still a common issue.
The answer to this question is in the cross-post on Stack Overflow. Note although it refers to the "systemd udev" service (applicable on pidora, Raspbian jessie, etc.) there is a parallel service on Raspbian wheezy (see
[Direct cut n' paste from the above link.]
From a kernel perspective, the 'value' files for each GPIO pin that has been exported are created with mode 0644 and ownership root:root. The kernel does not do anything to change this when you write to the 'direction' file.
The behavior you are describing is due to the operation of the systemd udev service. This service listens for events from the kernel about changes in device state, and applies rules accordingly.
When I tested on my own Pi, I did not experience the behavior you described - the gpio files in /sys are all owned by root:root and have mode 0644, and did not change regardless of direction. However I am running Pidora, and I could not find any udev rules in my system relating to this. I am assuming that Raspbian (or maybe some package you have added to your system) has added such rules.
I did find this thread where some suggested rules are mentioned. In particular this rule which would have the effect you describe:
SUBSYSTEM=="gpio*", PROGRAM="/bin/sh -c 'chown -R root:gpio /sys/class/gpio; chmod -R 770 /sys/class/gpio; chown -R root:gpio /sys/devices/virtual/gpio; chmod -R 770 /sys/devices/virtual/gpio'"
You can search in /lib/udev/rules.d, /usr/lib/udev/rules.d and /etc/udev/rules.d for any files containing the text 'gpio' to confirm if you have such rules. By the way, I would be surprised if the change was triggered by changing direction on the pin, more likely by the action of exporting the pin to userspace.
The reason you need to sleep for a while after exporting the device is that until your process sleeps, the systemd service may not get a chance to run and action the rules.
The reason it is done like this, rather than just having the kernel take care of it, is to push policy implementation to userspace in order to provide maximum flexibility without overly complicating the kernel itself.
See: systemd-udevd.service man page and udev man page.
[End cut n' paste]
On the last Raspbian image I checked, the relevent
udev rules can be found with:
grep gpio /lib/udev/rules.d/*
Again, this still doesn't affect restrictions on
unexport. This is probably a good precaution -- it means it takes privileges to export a pin, but once done, anyone in the
gpio group (which should include user
pi) can use it.