Linux的timerfd分析

來源:互聯網
上載者:User
文章目錄
  • 1.      使用方法
  • 2.      核心實現

http://blog.csdn.net/walkingman321/article/details/6162055

timerfd是Linux為使用者程式提供的一個定時器介面。這個介面基於檔案描述符,所以能夠被用於select/poll的應用情境。

1.      使用方法

timerfd提供了如下介面供使用者使用

timerfd_create

int timerfd_create(int clockid, int flags);

timerfd_create用於建立一個定時器檔案。

參數clockid可以是CLOCK_MONOTONIC或者CLOCK_REALTIME。

參數flags可以是0或者O_CLOEXEC/O_NONBLOCK。

函數傳回值是一個檔案控制代碼fd。

timerfd_settime

int timerfd_settime(int ufd, int flags, const struct itimerspec * utmr, struct itimerspec * otmr);

此函數用於設定新的逾時時間,並開始計時。

參數ufd是timerfd_create返回的檔案控制代碼。

參數flags為1代表設定的是絕對時間;為0代表相對時間。

參數utmr為需要設定的時間。

參數otmr為定時器這次設定之前的逾時時間。

函數返回0代表設定成功。

timerfd_gettime

int timerfd_gettime(int ufd, struct itimerspec * otmr);

此函數用於獲得定時器距離下次逾時還剩下的時間。如果調用時定時器已經到期,並且該定時器處於迴圈模式(設定逾時時間時struct itimerspec::it_interval不為0),那麼調用此函數之後定時器重新開始計時。

read

當timerfd為阻塞方式時,read函數將被阻塞,直到定時器逾時。

函數傳回值大於0,代表定時器逾時;否則,代表沒有逾時(被訊號喚醒,等等)。

poll/close

poll,close與標準檔案操作相同。

2.      核心實現

timerfd的核心實現代碼在kernel/fs/timerfd.c,它的實現基於Linux的hrtimer。

timerfd_create的實現

SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)

l         做一些定時器的初始化工作

l         調用hrtimer_init初始化一個hrtimer

l         調用anon_inode_getfd分配一個dentry,並得到一個檔案號fd,同時傳入timerfd的檔案操作指標struct file_operations timerfd_fops。anno_inode_getfd是檔案系統anon_inodefs的一個協助函數。anon檔案系統比較簡單,整個檔案系統只有一個inode節點,其實現代碼可以在fs/anon_inodes.c中找到。

timerfd_settime的實現

timerfd_settime最終會調用hrtimer_start啟動定時器,其逾時函數被設定為timerfd_tmrproc。

timerfd_tmrproc

timefd_tmrproc是timerfd的定時器逾時函數。在timerfd逾時時,該函數會設定定時器逾時標記位;增加定時器逾時次數(在設定定時器迴圈模式時,可能會出現多次逾時沒有被處理的情況);喚醒一個等待隊列,從而喚醒可能存在的正被阻塞的read、select。

timerfd_fops

static const struct file_operations timerfd_fops = {

       .release    = timerfd_release,

       .poll        = timerfd_poll,

       .read              = timerfd_read,

};

timerfd_read函數是檔案操作read的核心實現,讀到的是定時器的逾時次數。該函數在阻塞模式下會把自身掛到timerfd的等待隊列中,等待定時器逾時時被喚醒。

timerfd_poll將timerfd的等待隊列登記到一個poll_table,從而在定時器逾時時能喚醒select系統調用。

timerfd_release

timerfd_release函數釋放timerfd_create函數中申請的資源,刪除已指派的定時器。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.