实验四 软中断信号及处理
创始人
2024-04-10 23:48:18
0

1.利用sleep、pause、alarm函数设定闹钟,定时显示信息。

#include
#include
#include
#include
int main(){int ret;alarm(50);sleep(30);ret=alarm(10);printf("%d\n",ret);pause();printf("I have been waken up.\n"); 
}

阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?此时alarm还剩下多少时间?
发出SIGALRM信号,10s
问题2:蓝色部分的含义是什么?
挂起进程,直到捕捉到一个信号
问题3:程序的运行结果是什么,为什么运行结果中没有最后一个printf语句的输入内容?
在这里插入图片描述

因为进程没有被唤醒就被终止了
问题4:请在该程序上添加一个signal()函数捕捉信号,并进行信号处理,使程序显示“I have been waken up”。

#include
#include
#include
#include
int main(){int ret;alarm(50);sleep(30);ret=alarm(10);printf("%d\n",ret);signal(SIGALRM,alarm);pause();printf("I have been waken up.\n"); 
}

2.父进程通过kill()向子进程发送信号

#include 
#include 
#include 
#include 
#include 
#include 
int main(){ pid_t pid; pid=fork(); if(pid<0){ perror("fork() error\n");  } if(pid==0){printf("child process wait for signal!\n"); pause();}else{ sleep(3); kill(pid,SIGKILL);	printf("parent process send signal to kill child process!\n"); //waitpid(pid,NULL,0);printf("child process exit!\n"); exit(0); }
}

阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?
等待pid退出
问题2:若不添加红色程序会出现什么情况?
运行了多次,没有出现什么情况,可能主进程会先于子进程结束(但我没有运行出这个结果)

3.编制一段程序,使其实现进程的软中断通信

要求:使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按ctrl-c键);当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child process 1 is killed by parent!
Child process 2 is killed by parent!
父进程等待两个子进程终止后,输出如下的信息后终止:
Parent process is killed!

#include 
#include 
#include void waiting();
void stop();
void keep_alive();
int wait_mark;int main(){int p1,p2;while((p1=fork())==-1);if(p1>0){while((p2=fork())==-1);if(p2>0){printf("parent\n");wait_mark=1;signal(SIGINT, stop);  waiting();kill(p1, SIGINT);kill(p2, SIGINT);wait(0);wait(0);printf("parent process is killed children and exit!\n");exit(0); }else{printf("p2\n");//wait_mark=1;signal(SIGINT, keep_alive);pause();printf("child process2 is killed by parent!\n");exit(0);}}else{printf("p1\n");//wait_mark=1;signal(SIGINT, keep_alive);pause();printf("child process1 is killed by parent!\n");exit(0);}
}
void waiting(){while(wait_mark!=0);
}
void stop(){wait_mark=0;
}
void keep_alive(){
}

阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?
接收Ctrl+C
问题2:程序的运行结果是什么?
在这里插入图片描述

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...