在linux環境程式設計下,我們可以具體的限制一個程序對資源的使用,當程序嘗試超過資源使用的限制,它可能會收到一個信号,或是因資源而失敗的系統調用。每個程序最初的獲得的限制來自父程序,但是後來可以更改這個限制。
有兩個關于資源限制的概念:
current limit:為系統規定的上限,也叫做"soft limit",因為程序通常将被限制在這個範圍内。
maxinum limit:為一個程序被允許建立current limit的最大值,也叫做"hard limit",因為一個程序無法避開它,一個程序低于他自己的maxinum limit,且隻有超級使用者可能提高它的maxinum limit。
struct rlimit {
rlim_t rlim_cur;
//the current limit
rlim_t rlim_max;
//the maximum limit.
};
使用getrlimit,setrlimit,getrlimit64,setrlimit64(定義在<sys/resource.h>)來對上面兩個值進行使用。
— function: int getrlimit (int
resource, struct rlimit *rlp)
讀取類型為resource的限制值,并儲存在rlp中。
傳回值為0時成功,-1時失敗。失敗時可能将errno設定為efault.
— function: int setrlimit (int
resource, const struct rlimit *rlp)
更新新的current limit 與 maxinum limit限制 ,參數resource為限制的類型(下方有參數表),*rlp帶更新的結構體。
同樣成功傳回0,失敗傳回-1.将errno設定為eperm有如下兩種情況
1.設定的current limit 超過了maxinum limit的值。
2.在不是超級使用者的情況下設定了maxinum limit。
同時這裡隻提到
struct rlimit64{
rlim64_t rlim_cur;
//this is analogous to <code>rlimit.rlim_cur</code>, but with a different type.
<code>rlim64_t rlim_max</code>
//this is analogous to <code>rlimit.rlim_max</code>, but with a different type.
}
下面是具體可以限制的種類也就是resource清單
rlimit_cpu cpu使用時間限制,如果運作時間長于該值,将會收到信号:sigxcpu 該值以秒計量
rlimit_fsize 程序可建立檔案大小限制,如果程序嘗試寫更大的檔案将會受到信号:sigxfsz
rlimit_data 最大記憶體使用限制,如果程序嘗試配置設定記憶體并超出這個範圍,配置設定函數将會失敗
rlimit_stack 程序使用棧的大小限制,如果程序嘗試擴充它的棧并超過這個值,那個會收到信号<code>sigsegv</code>
rlimit_core 程序建立core檔案大小限制,如果程序結束并且要存儲core檔案高于該值,那麼core檔案不會被建立,是以設定這個值為0回保證core檔案從不被建立
rlimit_rss 程序所能得到的最大實體記憶體,這個參數是系統排程程式和記憶體配置設定的向導,系統在有盈餘時将會給程序更多的記憶體
rlimit_memlock
在實體記憶體中最大被鎖記憶體數
rlimit_nproc
同一使用者id建立最大程序數,如果已經到達最大程序數再調用fork會失敗
<code>rlimit_nofile</code>
<code>rlimit_ofile 程序可開最大檔案數,如果超出最大數将會失敗,該值存在在gnu 和 4.4bsd,部分系統沒有。</code>
<code>rlimit_as 程序總共可獲得的最大記憶體數,如果程序嘗試配置設定更多記憶體,那麼配置設定函數将會失敗。</code>
<code>rlim_nlimits 所有參數值的限制,以上任何參數值都不能高于該值</code>
<code></code>
<code>— constant: rlim_t rlim_infinity</code>該常量被定義為無窮,在調用setrlimit的時候
轉載請注明出處謝謝