【操作系統】 編制實現軟中斷通信的程序


實驗內容

1)       編制實現軟中斷通信的程序

  使用系統調用fork()創建兩個子進程,再用系統調用signal()讓父進程捕捉鍵盤上發出的中斷信號(即按delete鍵),當父進程接收到這兩個軟中斷的某一個后,父進程用系統調用kill()向兩個子進程分別發出整數值為16和17軟中斷信號,子進程獲得對應軟中斷信號,然后分別輸出下列信息后終止:

Child process 1 is killed by parent !!  

Child process 2 is killed by parent !!  

父進程調用wait()函數等待兩個子進程終止后,輸入以下信息,結束進程執行:

Parent process is killed!!

多運行幾次編寫的程序,簡略分析出現不同結果的原因。

代碼:

#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
#include<linux/input.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define NUM 2
#define DEV_PATH "/dev/input/event0"
int childpid[NUM],i,keys_fd;
struct input_event t;//event input
void die(){printf("\nChild press%d is killed by parent!\n",i);exit(0);}//child process die
void fatherfun(){//father process
    keys_fd=open(DEV_PATH, O_RDONLY);//open keyboard event file
    while(1)if(read(keys_fd, &t, sizeof(t))==sizeof(t))if(t.code==111)break;//wait "DELETE" key
    for(i=0;i<NUM;i++)kill(childpid[i],17);//kill all child
    close(keys_fd);//close file
    while(wait(NULL)!=-1);//make sure all child is killed
    printf("Parent process is killed\n");
}
void childfun(){//son process
    signal(17,die);//sign
    while(1);//wait signal
}
int main(){
    for(i=1;i<=NUM;i++)if(childpid[i-1]=fork()){if(i==NUM)fatherfun();}else{childfun();break;}//make child
    return 0;
}

 參考:

https://blog.csdn.net/liuxuejiang158blog/article/details/9057135

https://www.cnblogs.com/yangwindsor/articles/3454955.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM