How to get Linux distribution name and version?

2020-05-23 03:32发布

问题:

In Windows I read the registry key SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName to get the full name and version of the OS.

But in Linux, the code

struct utsname ver;
uname(&ver);
retVal = ver.sysname;

returns the string linux, not Ubuntu 9.04.

How can I get the Linux distribution name and version?

回答1:

Try:

cat /etc/lsb-release

You can also try

lsb_release -a

Or:

cat /proc/version


回答2:

lsb_release -ds ; uname -mr

on my system yields the following from the bash (terminal) prompt:

Ubuntu 10.04.4 LTS
2.6.32-41-generic x86_64


回答3:

What's the purpose of getting that information?

If you're trying to detect some features or properties of the system (e.g. does it support some syscall or does it have some library), instead of relying on output of lsb_release you should either:

  • try to use given features and fail gracefully (e.g. dlopen for libraries, syscall(2) for syscalls and so on)
  • make it a part of your ./configure check if applicable (standard FOSS way of automatically recognizing system features/properties)

Note that the first way above applies even if your software is binary-only.

Some code examples:

  dl = dlopen(module_path, RTLD_LAZY);
  if (!dl) {
    fprintf(stderr, "Failed to open module: %s\n", module_path);
    return;
  }

  funcptr = dlsym(dl, module_function);
  if (!funcptr) {
    fprintf(stderr, "Failed to find symbol: %s\n", module_function);
    return;
  }
  funcptr();

  dlclose(dl);

You can even gracefully test for CPU opcodes support, read e.g. http://neugierig.org/software/chromium/notes/2009/12/flash-lahf.html , http://code.google.com/p/chromium/issues/detail?id=29789



回答4:

Not sure I followed exactly what you're after but I think you just want the "all" flag on uname:

uname -a


回答5:

trying this way is an interesting one and less restrictive than lsb-release.

$ cat /etc/*-release


回答6:

Usually:

cat /etc/issue


回答7:

/etc/os-release is available on at least both CentOS 7 and Ubuntu 16.04, which makes it more cross-platform than lsb_release (not on CentOS) or /etc/system-release (not on Ubuntu).

$ cat /etc/os-release

Example:

NAME=Fedora
VERSION="17 (Beefy Miracle)"
ID=fedora
VERSION_ID=17
PRETTY_NAME="Fedora 17 (Beefy Miracle)"
ANSI_COLOR="0;34"
CPE_NAME="cpe:/o:fedoraproject:fedora:17"
HOME_URL="https://fedoraproject.org/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"


标签: c++ c linux api