实验八 Linux进程间通信
实验目的
学习和掌握Linux信号概念,并能使用系统调用完成电子表计时程序。
学习和掌握Linux进程间通信的IPC方法。
学习和掌握利用信号量实现进程间的同步通信。
实验内容
Linux信号
输入程序8-1,8-2编译并运行写出执行结果。
8-1结果
8-2结果
对比执行结果,你得到的启示是:
区别在于,8_2中ouch函数中又进行安装信号函数。即当ouch函数捕获外部中断的SGIINT信号后,改变安装信号函数(接受中断信号,进程结束)
利用Linux信号SIGALAM,设计并实现电子表程序。
#include <>
#include <>
int second=0,minutes=0,hour=0;
void time(){
alarm(1);
second++;
if(second>=60){
second=0;
minutes++;
}
if(minutes>=60){
hour++;
minutes=0;
}
printf("time: %d:%d:%d\r",hour,minutes,second);
fflush(stdout);
}
int main(){
signal(SIGALRM,time);//产生SIGALRM信号便调用time函数
raise(SIGALRM);
while(1){
}
return 0;
}
IPC方法—管道
双向管道实现聊天室功能,原理图如下!!!!
IPC方法—命名管道(FIFO)
输入程序8-4,8-5编译并运行写出执行结果。
IPC方法—信号量
输入程序8-6 -7 ,编译执行并写出结果。
IPC方法—内存映射
输入程序8-8和8-9,编译执行并写出结果。
_fd = open(filenm, O_RDWR | O_CREAT);
mmap_addr = (char *)mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
_________________________________________________________________________________mmap函数中,0表示有系统分配映射内存的地址;__4096,表示映射内存大小为4096B,
PROT_READ|PROT_WRITE表示允许程序对内存读写操作,MAP_SHARED表示对内存的操作对其他程序来说是可见的。
IPC方法—共享内存
输入程序8-10和8-11,编译执行并写出结果。
简述程序8-10和8-11,是否实现了共享内存互斥访问,如何实现?
IPC方法—消息队列
输入程序8-12和8-13,编译执行并写出结果。
主要仪器设备及软件
硬件:计算机、网络
软件:VMWare workstation、RedHat
附录:程序清单
8-1
#include <>
#include <>
#include <>
void ouch(int sig)
{
printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
struct sigaction act;
= ouch;
sigemptyset(&);
= 0;
sigaction(SIGINT, &act, 0);
while(1) {
printf("Hello World!\n");
sleep(1);
}
}
8-2
#include <>
#include <>
#include <>
void ouch(int sig)
{
printf("OUCH! - I got signal %d\n", sig);
(void) signal(SIGINT, SIG_DFL);
}
int main()
{
(void) signal(SIGINT, ouch);
while(1) {
printf("Hello World!\n");
sleep(1);
}
}
8-3—
#include <>
#include <sys/>
2008110360余明华 来自淘豆网m.daumloan.com转载请标明出处.