1. 程式人生 > 實用技巧 >【作業系統】程序管理實驗

【作業系統】程序管理實驗

實驗內容

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; void die(){printf("\nChild press%d is killed by parent!\n",i);exit(0);} void fatherfun(){ keys_fd=open(DEV_PATH, O_RDONLY); while(1)if(read(keys_fd, &t, sizeof(t))==sizeof(t))if(t.code==111)break; for(i=0;i<NUM;i++)kill(childpid[i],17); close(keys_fd);
while(wait(NULL)!=-1); printf("Parent process is killed\n"); } void childfun(){ signal(17,die); while(1); } int main(){ for(i=1;i<=NUM;i++)if(childpid[i-1]=fork()){if(i==NUM)fatherfun();}else{childfun();break;} return 0; }