You are not logged in.
Pages: 1
I have a shell script that updates brightness using echo [number] > /location/of/brightness. It works okay when it's run as root. Also, as root, I can adjust the brightness value using an editor like nano.
A few minutes ago, I tried to translate this into a simple C program. It compiled fine. However, when I tried running the program as root, it gave a "Segmentation fault" as the result, and did not change the brightness.
Can anyone offer any pointers?
Here's the code:
#include <stdio.h>
#include <fcntl.h> // Use "open"
#include <unistd.h> // For "close"
int main() {
// Open the brightness file.
FILE *fp = fopen("/sys/class/backlight/acpi_video0/test", "w+");
// Adjust brightness value.
fprintf(fp, "5");
// End.
fclose(fp);
return 0;
}
Last edited by siva (2019-12-13 03:56:16)
Offline
might be some pointers here: https://www.linuxquestions.org/question … 175521454/
Offline
siva, change test to brightness so that the source file looks like this:
#include <stdio.h>
#include <fcntl.h> // Use "open"
#include <unistd.h> // For "close"
int main() {
// Open the brightness file.
FILE *fp = fopen("/sys/class/backlight/acpi_video0/brightness", "w+");
// Adjust brightness value.
fprintf(fp, "5");
// End.
fclose(fp);
return 0;
}
Then compile the file, change ownership to root, and set SUID:
$ gcc -o testing testing.c
$ sudo chown root:root testing
$ sudo chmod u+s testing
Now run the executable as regular user and it will change the brightness:
$ ./testing # boom! brightness changes
It was segfaulting because the binary did not have enough permissions to open the file.
Last edited by GNUser (2019-12-13 15:03:52)
Offline
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
int opt;
FILE *fp;
char *fname = NULL;
char *brightness = NULL;
while ((opt = getopt(argc, argv, "b:f:")) != -1) {
switch (opt) {
case 'b':
brightness = optarg;
break;
case 'f':
fname = optarg;
break;
default:
fname = brightness = NULL;
}
}
if (fname && brightness) {
if((fp = fopen(fname, "w+")) != NULL) {
if (fprintf(fp, "%s", brightness) > 0) {
fclose(fp);
exit(EXIT_SUCCESS);
}
}
fprintf(stderr, "%s: %s: '%s'\n", argv[0], strerror(errno), fname);
} else {
fprintf(stderr, "Usage: %s -f PATH -b NUM\n"
"Options: -f\t\tsysfs path\n"
" -b\t\tbrightness value\n", argv[0]);
}
exit(EXIT_FAILURE);
}
Just for fun and to refresh my C coding skills. Improved version with command line arguments handling and error checking.
Ciao
Offline
Pages: 1