You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.9 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. static char *argv0 = "./backlight";
  6. static char *backlight_file = "/sys/devices/platform/backlight/backlight/backlight/brightness";
  7. void print_usage()
  8. {
  9. printf("usage: %s COMMAND [VALUE]\n", argv0);
  10. printf(" COMMAND = {get, set}\n");
  11. printf(" get ... prints current backlight level\n");
  12. printf(" set ... sets backlight level to VALUE\n");
  13. printf(" VALUE = [0..10] ... backlight amount\n");
  14. }
  15. void print_usage_and_fail()
  16. {
  17. print_usage();
  18. exit(EXIT_FAILURE);
  19. }
  20. void command_get()
  21. {
  22. FILE *fp = fopen(backlight_file, "r");
  23. if (fp == NULL) {
  24. fprintf(stderr, "Cannot open file '%s' for reading.\n", backlight_file);
  25. exit(EXIT_FAILURE);
  26. }
  27. int buffer_length = 255;
  28. char buffer[buffer_length];
  29. while (fgets(buffer, buffer_length, fp)) {
  30. printf("%s", buffer);
  31. }
  32. fclose(fp);
  33. }
  34. void command_set(int value)
  35. {
  36. if (setuid(0)) {
  37. fprintf(stderr, "Cannot set root permissions via setuid(0).\n");
  38. exit(EXIT_FAILURE);
  39. }
  40. FILE *fp = fopen(backlight_file, "w+");
  41. if (fp == NULL) {
  42. fprintf(stderr, "Cannot open file '%s' for writing.\n", backlight_file);
  43. exit(EXIT_FAILURE);
  44. }
  45. fprintf(fp, "%d\n", value);
  46. fclose(fp);
  47. }
  48. int main(int argc, char *argv[])
  49. {
  50. if (argc < 1) {
  51. print_usage_and_fail();
  52. }
  53. argv0 = argv[0];
  54. if (argc < 2) {
  55. print_usage_and_fail();
  56. }
  57. char *command = argv[1];
  58. if ((strcmp(command, "get") == 0) && (argc == 2)) {
  59. command_get();
  60. } else if ((strcmp(command, "set") == 0) && (argc == 3)) {
  61. int value = atoi(argv[2]);
  62. if (value < 0 || value > 10) {
  63. print_usage_and_fail();
  64. }
  65. command_set(value);
  66. } else {
  67. print_usage_and_fail();
  68. }
  69. exit(EXIT_SUCCESS);
  70. }