今天看了mingetty open source,在里面看到有uname这个函数能够获取一些我们有时需要的信息,如操作系统,版本,发行版,机器型号等等。现改了一下,帖出来,供大家分享。
Name: uname.c
/************************************************************/
#include <stdio.h>
#include <utmp.h>
#include <sys/utsname.h>
#include <time.h>
#include <sys/stat.h>
static void output_special_char(unsigned char c)
{
static struct utsname uts; // The struct in the <sys/utsname.h>.
uname (&uts);
switch (c) {
case 's':
printf("sysname:%s\n", uts.sysname);
break;
case 'n':
printf("nodename:%s\n", uts.nodename);
break;
case 'r':
printf("release:%s\n", uts.release);
break;
case 'v':
printf("version:%s\n", uts.version);
break;
case 'm':
printf("machine:%s\n", uts.machine);
break;
case 'o':
//printf("domainname:%s\n", uts.__domainname); //Please read sys/utsname.h,must be define USE_GNU
break;
case 'd':
case 't':
{
time_t cur_time;
struct tm *tm;
time(&cur_time);
tm = localtime(&cur_time);
if (c == 'd') /* ISO 8601 */
printf("dtime:%d-%02d-%02d\n", 1900 + tm->tm_year,
tm->tm_mon + 1, tm->tm_mday);
else
printf("ttime:%02d:%02d:%02d\n", tm->tm_hour, tm->tm_min,
tm->tm_sec);
break;
}
case 'u':
case 'U':
{
int users = 0;
struct utmp *ut;
setutent();
while ((ut = getutent()))
if (ut->ut_type == USER_PROCESS)
users++;
endutent();
printf("%d\n", users);
if (c == 'U')
printf(" user%s\n", users == 1 ? "" : "s");
break;
}
default:
putchar(c);
}
}
int main(int argc, char **argv)
{
output_special_char('s');
output_special_char('n');
output_special_char('r');
output_special_char('v');
output_special_char('m');
output_special_char('o');
output_special_char('d');
output_special_char('t');
output_special_char('u');
output_special_char('U');
return 0;
}
/************************************************************/ Compile: gcc uname.c
Run: ./a.out
Result:
--------------------------------------------------------------------------
sysname:Linux
nodename:wirejet41.flowelltech.com.cn
release:2.6.21-1.3194.fc7
version:#1 SMP Wed May 23 22:35:01 EDT 2007
machine:i686
dtime:2009-01-05
ttime:17:21:29
1
1
user
--------------------------------------------------------------------------
关键字:系统 参数 Linux uname函数
--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/