How to get Linux distribution name and version?

2020-05-23 03:26发布

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?

标签: c++ c linux api
7条回答
对你真心纯属浪费
2楼-- · 2020-05-23 04:06

Usually:

cat /etc/issue
查看更多
够拽才男人
3楼-- · 2020-05-23 04:08

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

uname -a
查看更多
ゆ 、 Hurt°
4楼-- · 2020-05-23 04:17

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

$ cat /etc/*-release
查看更多
放我归山
5楼-- · 2020-05-23 04:17

/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/"
查看更多
We Are One
6楼-- · 2020-05-23 04:19
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
查看更多
Lonely孤独者°
7楼-- · 2020-05-23 04:21

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

查看更多
登录 后发表回答