sysfs.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "util.h"
  2. #include "sysfs.h"
  3. static const char * const sysfs_known_mountpoints[] = {
  4. "/sys",
  5. 0,
  6. };
  7. static int sysfs_found;
  8. char sysfs_mountpoint[PATH_MAX];
  9. static int sysfs_valid_mountpoint(const char *sysfs)
  10. {
  11. struct statfs st_fs;
  12. if (statfs(sysfs, &st_fs) < 0)
  13. return -ENOENT;
  14. else if (st_fs.f_type != (long) SYSFS_MAGIC)
  15. return -ENOENT;
  16. return 0;
  17. }
  18. const char *sysfs_find_mountpoint(void)
  19. {
  20. const char * const *ptr;
  21. char type[100];
  22. FILE *fp;
  23. if (sysfs_found)
  24. return (const char *) sysfs_mountpoint;
  25. ptr = sysfs_known_mountpoints;
  26. while (*ptr) {
  27. if (sysfs_valid_mountpoint(*ptr) == 0) {
  28. sysfs_found = 1;
  29. strcpy(sysfs_mountpoint, *ptr);
  30. return sysfs_mountpoint;
  31. }
  32. ptr++;
  33. }
  34. /* give up and parse /proc/mounts */
  35. fp = fopen("/proc/mounts", "r");
  36. if (fp == NULL)
  37. return NULL;
  38. while (!sysfs_found &&
  39. fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n",
  40. sysfs_mountpoint, type) == 2) {
  41. if (strcmp(type, "sysfs") == 0)
  42. sysfs_found = 1;
  43. }
  44. fclose(fp);
  45. return sysfs_found ? sysfs_mountpoint : NULL;
  46. }