开发者

Using libblkid to find UUID of a partition

I was looking at libblkid and was confused about the documentation. Could someone provide me with an example of how I could f开发者_JAVA技巧ind the UUID of a root linux partition using this library?


It's pretty much as simple as the manual makes it look: you create a probe structure, initialize it, ask it for some information, and then free it. And you can combine the first two steps into one. This is a working program:

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[]) {
  blkid_probe pr;
  const char *uuid;

  if (argc != 2) {
    fprintf(stderr, "Usage: %s devname\n", argv[0]);
    exit(1);
  }

  pr = blkid_new_probe_from_filename(argv[1]);
  if (!pr) {
    err(2, "Failed to open %s", argv[1]);
  }

  blkid_do_probe(pr);
  blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);

  printf("UUID=%s\n", uuid);

  blkid_free_probe(pr);

  return 0;
}

blkid_probe_lookup_value sets uuid to point to a string that belongs to the pr structure, which is why the argument is of type const char *. If you needed to, you could copy it to a char * that you manage on your own, but for just passing to printf, that's not needed. The fourth argument to blkid_probe_lookup_value lets you get the length of the returned value in case you need that as well. There are some subtle differences between blkid_do_probe, blkid_do_safeprobe, and blkid_do_fullprobe, but in cases where the device has a known filesystem and you just want to pull the UUID out of it, taking the first result from blkid_do_probe should do.


First you need to find the device mounted as as root. See man getmntent (3). Once you know the device, use blkid_new_probe_from_filename as described by hobbs.

#include <stdio.h>
#include <mntent.h>

int main() {
    FILE* fstab = setmntent("/etc/mtab", "r");
    struct mntent *e;
    const char *devname = NULL;
    while ((e = getmntent(fstab))) {
        if (strcmp("/", e->mnt_dir) == 0) {
            devname = e->mnt_fsname;
            break;
        }
    }
    printf("root devname is %s\n", devname);
    endmntent(fstab);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜