【操作系统】 编制实现软中断通信的程序

实验内容

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

posted @ 2020-12-08 15:38  海底淤泥  阅读(1640)  评论(0编辑  收藏  举报