Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C how to use the function uname

Tags:

c

function

uname

I should write a function to get some information about the system (the most important information is the the architecture). I found the function uname which can be used including sys/utsname.h. Well, though I googled and I read the documentation, I couldn't find any example of the function and I don't understand how to use uname. Anyone can explain me how to use it? it would be great if you can write an example, too. Thanks in advance.

like image 335
En_t8 Avatar asked Aug 29 '10 19:08

En_t8


People also ask

What is uname function write a suitable C program?

The uname() function takes a pointer to the utsname structure that will store the result as input. Therefore, just make a temporary utsname instance, pass the address of it to uname , and read the content of this struct after the function succeed.

What does uname return?

As of OS/390® Release 2, the uname() function will return "OS/390" as the sysname value, even if the true name of the operating system is different. This is for compatibility purposes. The version value will increase at every new version of the operating system.

What is uname system call?

The uname system call fills a structure with various system information, including the computer's network name and domain name, and the operating system version it's running. Pass uname a single argument, a pointer to a struct utsname object. Include <sys/utsname.


2 Answers

First, include the header:

#include <sys/utsname.h>

Then, define a utsname structure:

struct utsname unameData;

Then, call uname() with a pointer to the struct:

uname(&unameData); // Might check return value here (non-0 = failure)

After this, the struct will contain the info you want:

printf("%s", unameData.sysname);

http://opengroup.org/onlinepubs/007908775/xsh/sysutsname.h.html

like image 186
Amber Avatar answered Sep 20 '22 16:09

Amber


A fully working example is worth a thousand words. ;-)

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#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;
}
like image 38
tupiniquim Avatar answered Sep 18 '22 16:09

tupiniquim