Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using libblkid to find UUID of a partition

Tags:

linux

uuid

I was looking at libblkid and was confused about the documentation. Could someone provide me with an example of how I could find the UUID of a root linux partition using this library?

like image 335
HighLife Avatar asked Jul 19 '11 14:07

HighLife


1 Answers

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.

like image 67
hobbs Avatar answered Nov 05 '22 02:11

hobbs