TL DR
I am writing a C program. I need root privileges for fopenthe sysfs file, and I still need root privileges to read them. However, since my program will need to continuously read the sysfs file, this means that all this time I will need to have elevated privileges. I would like to reset root privileges as soon as possible. What is an acceptable way to solve this problem?
More details
I am writing a program that interacts with sysfs. If I were to run commands on the shell, I would use:
myuser@mymachine:~$ sudo su
root@mymachine:/home/myhomedir
root@mymachine:/sys/class/gpio
root@mymachine:/sys/class/gpio
0
root@mymachine:/sys/class/gpio
I need to run these commands in a C program that can be invoked by a non-privileged user. One way to do this - to record a program in the usual way by using fopen, fprintf, fscanfetc. And run the program through sudo. However, this means that the user must be sudoer, and the program will have root privileges all the time.
Another solution that I prefer (since the user does not need to add to sudoers), it is necessary to change the owner of the program to root and set the bit setuid. (I learned this from here ).
, - . sysfs, euid 0, ( ). , , setuid() UID . , , . :
FILE *export = fopen("/sys/class/gpio/export", "wb");
fprintf(export, "971\n");
fclose(export);
FILE *sw_gpio = fopen("/sys/class/gpio971/value", "rb");
setuid(1000);
int switch_val = -1;
fscanf(sw_gpio, "%d", &switch_val);
printf("Switch value: %d\n", switch_val);
fclose(sw_gpio);
, , /sys/class/gpio/gpio971/value. , ! , root .
, , , :
-rwsr-xr-x 1 root myuser 10943 Jan 1 20:17 main*
, root, sysfs ?