1. 程式人生 > >linux 系統呼叫sysconf函式使用

linux 系統呼叫sysconf函式使用

在看開原始碼的時候,尤其是獲取cpu核數的時候,發現了一個很好用的一個函式

 #include <unistd.h>

       long sysconf(int name);

通過名字可以猜到,該函式是獲取一些系統的引數。然後通過man sysconf

我們可以知道該函式的使用條件,

 POSIX  allows an application to test at compile or run time whether certain options are supported, or what the value is of certain configurable
       constants or limits.


       At compile time this is done by including <unistd.h> and/or <limits.h> and testing the value of certain macros.


       At run time, one can ask for numerical values using the present function sysconf().  On can ask for numerical values that  may  depend  on  the
       file system a file is in using the calls fpathconf(3) and pathconf(3).  One can ask for string values using confstr(3).

大概 意思就是我們可以通過相關選項,來獲取編譯或者執行時的一些系統引數值。比如或許cpu核數,記憶體大小,一個程序大開啟檔案的大小

使用下面的一個例項,看一下我的電腦的一些配置資訊

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
	printf("Size of a page in bytes:%ld\n",sysconf(_SC_PAGESIZE));
	printf("Max length of a  hostname:%ld\n",sysconf(_SC_HOST_NAME_MAX));
	printf(" The maximum number of files that a process can have open at any time.:%ld\n",sysconf(_SC_OPEN_MAX));
	printf("  The  number  of  clock  ticks  per  second.:%ld\n",sysconf(_SC_CLK_TCK)); 
	printf("The number of processors currently online .:%ld\n",sysconf(_SC_NPROCESSORS_ONLN)); 
	printf("The number of processors configured..:%ld\n",sysconf(_SC_NPROCESSORS_CONF)); 
	return 0;
}
輸出資訊:
Size of a page in bytes:4096
Max length of a  hostname:64
 The maximum number of files that a process can have open at any time.:1024
  The  number  of  clock  ticks  per  second.:100
The number of processors currently online .:1
The number of processors configured..:1

這裡只列舉了一點點:具體還是要看man page裡的東西。