Identifying a Linux system in code

Since I got asteroids running on a Raspberry Pi, I have decided I want to incorporate the temperature in the window caption when you switch it to debug mod by pressing Tab. Currently all that does is display position info on moving objects and bounding boxes.

But if I include that code in, I want to be sure that it only works when running on a Raspberry Pi. So I need some code to identify the system. A bit of digging and I discovered the Linux uname command. That link goes to an online man page for uname.

If I run uname -a on my Ubuntu 18.04LTS I get this.

Linux david-Virtual-Machine 4.15.0-96-generic #97-Ubuntu SMP Wed Apr 1 03:25:46 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

And on my PI.

Linux raspberrypi 4.19.97-v7+ #1294 SMP Thu Jan 30 13:15:58 GMT 2020 armv7l GNU/Linux

In fact the uname -n command gives david-Virtual-Machine on Ubuntu and raspberrypi on the PI. These are the names though names are often changeable and what if someone is running ubuntu on a PI? Yes it is a thing. But the uname -m identifies the CPU.  x86-64 on my Ubuntu and armv71 on the pi.

I did a bit of digging and found a C program on stackoverflow that will do the same as uname.

#include 
#include 
#include 
#include <sys/utsname.h>

int main(void) {

   struct utsname buffer;

   errno = 0;
   if (uname(&buffer) != 0) {
      perror("uname");
      exit(EXIT_FAILURE);
   }

   printf("system name = %s\n", buffer.sysname);
   printf("node name   = %s\n", buffer.nodename);
   printf("release     = %s\n", buffer.release);
   printf("version     = %s\n", buffer.version);
   printf("machine     = %s\n", buffer.machine);

   #ifdef _GNU_SOURCE
      printf("domain name = %s\n", buffer.domainname);
   #endif

   return EXIT_SUCCESS;
}

And this is what it outputs on a PI.


system name = Linux
node name   = raspberrypi
release     = 4.19.97-v7+
version     = #1294 SMP Thu Jan 30 13:15:58 GMT 2020
machine     = armv7l

So that bit is easy to do. Next is getting the temperature, but that’s for another blog entry…

Leave a Reply

Your email address will not be published. Required fields are marked *