实验3 进程通信
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验三进程通信
学校:FJUT 学号:3131903229 班级:计算机1302 姓名:姜峰
一.实验学时与类型
学时:2,课外学时:自定
实验类型:设计性实验
二.实验目的
了解Linux的软中断、管道、消息队列、共享存储区等进程间通信方式。
三.实验内容
1. 软中断通信机制
(1) 请编写一个程序:循环输出“how are you?”,在按下Ctrl+C后中断显示,输出“Byebye!”后退出程序。
源代码:
#include
#include
int flag = 1;
void Soft_Interrupt()
{
flag = 0;
return;
}
int main()
{
signal( 2, Soft_Interrupt );
while( flag )
{
printf( "how are you?\n" );
}
printf( "Byebye!" );
return 0;
}
运行结果截图:
(2) 使用软中断机制实现父子进程同步,父进程先输出A,然后子进程输出B。源代码:
#include
#include
#include
int flag = 1;
void Soft_Interrupt()
{
flag = 0;
return;
}
int main()
{
int pid = fork();
if( pid > 0 )
{
printf( "I am father:A\n" );
kill( pid, 10 );
}
else if( pid == 0 )
{
signal( 10, Soft_Interrupt );
while( flag )
{
sleep( 1 );
}
printf( "I am child:B\n" );
}
else
{
printf( "EORROR!\n" );
return -1;
}
return 0;
}
运行结果截图:
2. 管道机制
(1) 父子进程通过管道传送一串字符。要求:子进程随机从键盘输入一串字符,通过管道发给父进程,父进程从管道中将消息读出并显示出来。
源代码:
#include
#include
#include
#include
int main()
{
int pid, flag, singlepipe[2];
char *writepipe, *readpipe;
flag = pipe( singelpipe );
if( flag == -1 )
{
printf( "ERRORPIPE!\n" );
return -1;
}
pid = fork();
if( pid > 0 )
{
readpipe = ( char * ) malloc( 100 * sizeof( char ) );
wait( 0 );
read( singlepipe[0], readpipe, 100 );
printf( "father:%s\n", readpipe );
}
else if( pid == 0 )
{
printf( "please input a period of string( stringlength<100 ):\n" );
writepipe = ( char * ) malloc( 100 * sizeof( char ) );
scanf( "%s", writepipe );
write( singlepipe[1], writepipe, strlen( writepipe ) );
}
else
{
printf( "ERRORFORK!\n" );
return 0;
}
return 1;
}
运行结果截图:
(2) 父子进程通过管道互相发送字符串。要求:子进程向父进程通过管道发送”I am child.”,父进程回送”I am father.”,父子进程将各自收到的字符串显示在屏幕上。源代码:
#include
#include
#include
#include
int main()
{
int pid, flag, singlepipe[2];
char *childpipe, *parentpipe;
childpipe = ( char * ) malloc( 15 * sizeof( char ) );
parentpipe = ( char * ) malloc( 15 * sizeof( char ) );
flag = pipe( singlepipe );
if( flag == -1 )
{
printf( "ERRORPIPE!\n" );
return -1;
}
pid = fork();
if( pid > 0 )
{
usleep( 100 );
read( singlepipe[0], childpipe, 15 );
printf( "child say:%s\n", childpipe );
strcpy( parentpipe, "I am father" );
write( singlepipe[1], parentpipe, strlen( parentpipe ) );
}
else if( pid == 0 )
{
strcpy( childpipe, "I am child." );