嵌入式作業系統核心原理和開發(系統中斷模擬)

來源:互聯網
上載者:User

【 聲明:著作權,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】

    在嵌入式作業系統中,最難模仿的是系統中斷的問題。在windows下面,這是沒有辦法的事情。但是在linux下面,卻有一個非常便利的條件,那就是linux的訊號處理。因為使用者程式處理的時候,signal的處理和使用者線程的處理堆棧是一致的,這和中斷是完全吻合的。所以,如果你需要關閉中斷,可以這麼寫,

sigprocmask(SIG_BLOCK, &new_set, &old_set);

    當然,如果需要再次開啟中斷了,還可以這麼寫,

sigprocmask(SIG_UNBLOCK, &new_set, NULL);

    所以,這裡我們可以編寫一個完整的程式說明問題。

#include <stdio.h>#include <time.h>#include <sys/time.h>#include <stdlib.h>#include <signal.h>static int count = 0;static struct itimerval oldtv;void set_timer(){struct itimerval itv;itv.it_interval.tv_sec = 1;itv.it_interval.tv_usec = 0;itv.it_value.tv_sec = 1;itv.it_value.tv_usec = 0;setitimer(ITIMER_REAL, &itv, &oldtv);}void signal_handler(int m){count ++;printf("%d\n", count);}void signal_int(){    printf("hello!\n");}int main(){    sigset_t new_set;    sigset_t old_set;    signal(SIGALRM, signal_handler);    signal(SIGINT,  signal_int);    set_timer();    sigemptyset(&new_set);    sigaddset(&new_set, SIGALRM);    sigaddset(&new_set, SIGINT);    sigprocmask(SIG_BLOCK, &new_set, &old_set);    sleep(10);        sigprocmask(SIG_UNBLOCK, &new_set, NULL);    while(count < 10 ) sleep(1);    return 0;}

    基本說明如下:

    (1)我們的系統暫時只負責SIGINT和SIGALRM,前者負責I/O的模擬,後則負責線程的調度;

    (2) sigprocmask函數用來實現中斷的開啟和關閉;

    (3)程式首先關閉中斷,然後開啟中斷,列印資料完即結束,僅作為示範使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.