实验三进程通信

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

实验三进程通信

一.实验学时与类型

学时:2,课外学时:自定

实验类型:设计性实验

二.实验目的

了解Linux的软中断、管道、消息队列、共享存储区等进程间通信方式。

三.实验容

1. 软中断通信机制

(1) 请编写一个程序:循环输出“how are you?”,在按下Ctrl+C后中断显示,输出“Byebye!”后退出程序。

#include

#include

int k=1;

void int_func(int sig) //软中断处理函数

{ k=0; }

Int main()

{ signal(SIGINT,int_func);//预置软中断信号处理函数

While(k==1)

Printf(“how are you?\n”);

Printf(“byebye!”);

}

(2)使用信号机制实现父子进程同步,父进程先输出A,然后子进程输出B。

#include

#include

int k=1;

void func(int sig) { k=0; }

main()

{ int pid;

pid=fork();

if(pid>0)

{ printf(“A\n”);

kill(pid,12);

}

else if(pid==0)

{ signal(12,func);

while(k==1)

sleep(1);

printf(“B\n”);

}

}

2. 管道机制

(1) 父子进程通过管道传送一串字符。要求:子进程随机从键盘输入一串字符,通过管道发给父进程,父进程从管道中将消息读出并显示出来。

#include

#include

main()

{ int pid, fd[2] ;

char outpipe[50], inpipe[50];

pipe(fd);

pid=fork();

if (pid==0)

{

Printf(“please input some message:\n”);

Fgets(inpipe,sizeof(inpipe),stdin);

write(fd[1],inpipe,50);

}

else if (pid>0);

{ wait(0);

Printf(“father get this message:\n”);

read(fd[0],outpipe,50);

printf(“%s\n”,outpipe);

}

}

(2)父子进程通过管道互相发送字符串。要求:子进程向父进程通过管道发送”I am child.”,父进程回送”I am father.”,父子进程将各自收到的字符串显示在屏幕上。

#inlcude

#include

#include

main()

{ int pid, fd[2] ;

char str1[50], str2[50];

pipe(fd);

pid=fork();

if (pid==0)

{ strcpy(str1,”I’m child”);

write(fd[1],str1,strlen(str1));

Sleep(1);

read(fd[0],str2,50);

printf(“Child received: %s\n”,str2);

}

else if (pid>0)

{ read(fd[0],str1,50);

printf(“Parent received:%s\n”,str1);

strcpy(str2,”I’m father.”);

write(fd[1],str2,strlen(str2));

}

}

3. 消息队列机制

(1) 父进程及其子进程通过一条消息队列互相传送数据。

#include

#include

#include

#include

int msgqid,qid;

struct msg

{ long mtype;

char mtext[256];

}pmsg;

cancelqueue()

{ msgctl(msgqid,IPC_RMID,0);

exit(0);}

main()

{ int pid;

Pid=fork();

If (pid>0)

{ msgqid=msgget(75, 0777);

printf(“msg id: %d\n”,msgqid);

pmsg.mtype=1;

*((int *)pmsg.mtext)=getpid();

msgsnd(msgqid,&pmsg,sizeof(int),0);

msgrcv(msgqid,&pmsg,256,getpid(),0);

printf(“A:receive msg from %d\n",*((int *)pmsg.mtext)); }

Else if(pid==0)

{ signal(2,cancelqueue);

msgqid=msgget(75, 0777|IPC_CREAT);

while(1)

{ msgrcv(msgqid,&pmsg,256,1,0);

qid=*(int *)pmsg.mtext;

printf(“B:receive msg from %d\n”,qid);

pmsg.mtype=qid;

*((int *)pmsg.mtext)=getpid();

msgsnd(msgqid,&pmsg,sizeof(int),0);

}

}

}

(2) 非父子进程之间实通过一条消息队列互相传递数据。

A进程:

#include

相关文档
最新文档