实验三 进程间通信

  • 格式:doc
  • 大小:262.00 KB
  • 文档页数:14

下载文档原格式

  / 14
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验三进程间通信(2学时)

一、实验目的

(1)了解什么是信号。

(2)熟悉LINUX系统中进程之间软中断通信的基本原理。

(3)熟悉LINUX支持的管道通信方式。

二、实验内容

(1)编写一段程序,使其现实进程的软中断通信。

即:使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按 ctrl+c 键);当捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后,分别输出下列信息后终止:

Child Process11 is killed by Parent!

Child Process12 is killed by Parent!

父进程等待两个子进程终止后,输出如下的信息后终止

Parent Process is killed!

要求:运行以下参考程序并分析结果。

<参考程序>

#include

#include

#include

#include

void waiting(),stop(),alarming();

int wait_mark;

main()

{

int p1,p2;

if(p1=fork()) /*创建子进程p1*/

{

if(p2=fork()) /*创建子进程p2*/

{ //父进程

wait_mark=1;

signal(SIGINT,stop); /*接收到^c信号,转stop*/

signal(SIGALRM,alarming);/*接受SIGALRM*/

waiting();

kill(p1,16); /*向p1发软中断信号16*/

kill(p2,17); /*向p2发软中断信号17*/

wait(0); /*同步*/

wait(0);

printf("parent process is killed!\n");

exit(0); //会暂时停止目前进程的执行,直到有信号来到或子进程结束。

}

else

{

wait_mark=1;

signal(17,stop);

signal(SIGINT,SIG_IGN); /*忽略 ^c信号*/

while (wait_mark!=0);

lockf(1,1,0);

printf("child process2 is killed by parent!\n");

lockf(1,0,0);

exit(0);

}

}

else

{

wait_mark=1;

signal(16,stop);

signal(SIGINT,SIG_IGN); /*忽略^c信号*/

while (wait_mark!=0);

lockf(1,1,0);

printf("child process1 is killed by parent!\n");

lockf(1,0,0);

exit(0);

}

}

void waiting()

{

sleep(5);

if (wait_mark!=0)

kill(getpid(),SIGALRM);

}

void alarming()

wait_mark=0;

}

void stop()

{

wait_mark=0;

}

(2)修改上面的程序

增加语句signal(SIGINT,SIG_IGN)和语句signal(SIGQUIT,SIG_IGN),再观察程序执行时屏幕上出现的现象,并分析其原因。这里,

signal(SIGINT,SIG_IGN)和signal(SIGQUIT,SIG_IGN)分别为忽略键信号以及忽略中断信号。

<程序>

#include

#include

#include

int pid1,pid2;

int EndFlag=0;

int pf1=0;

int pf2=0;

void IntDelete()

{

kill(pid1,16);

kill(pid2,17);

}

void Int1()

{

printf("child process 1 is killed !by parent\n");

exit(0);

}

void Int2()

{

printf("child process 2 is killed !by parent\n");

exit(0);

}

main()

{

int exitpid;

if(pid1=fork())

{

if(pid2=fork())

{

signal(SIGINT,IntDelete);

waitpid(-1,&exitpid,0);

waitpid(-1,&exitpid,0);

printf("parent process is killed\n");

exit(0);

}

else

{

signal(SIGINT,SIG_IGN);

signal(17,Int2);

pause();

}

}

else

{

signal(SIGINT,SIG_IGN);

signal(16,Int1);

pause();

}

}