操作系统实验——进程通信
2021/10/23 7:11:39
本文主要是介绍操作系统实验——进程通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
操作系统实验——进程通信
参考资料
- https://www.cnblogs.com/52php/p/5862114.html
- https://www.cnblogs.com/52php/p/5861372.html
1.实验要求
1、进程通信
编写一段程序,实现进程的管道通信。
使用系统调用 pipe()建立一条管道线:两个子进程 P1 和 P2 分别向管道各写一句话:
Child 1 is sending a message!
Child 2 is sending a message!
父进程则从管道中读出 来自两个子进程的信息,显示在屏幕上。
要求父进程先接收子进程 P1 发来的消息,然后再接收子进程 P2 发来的消息。(可以通过 sleep()将自身进入睡眠)
2、 消息的创建,发送和接收.
(1) 使用系统调用 msgget(), msgsnd(), msgsrv()及 msgctl()编制一长度为 1K 的消息(如个人通信录信息)的发送和接收程序.
① 观察上面程序,说明控制消息队列系统调用 msgctl()
② 共享存储区的发送和接收。
(2) 使用共享存储区相关的系统调用 shmget(),shmat(),sgmdt(),shmctl(),编制一个与上述功能相同的程序.
(3) 比较上述两种消息通信机制中数据传输的时间。
2.管道通信
- 代码实现
#include<stdio.h> #include <stdlib.h> int main() { int id,fd[2],pid; char buf[50],s[50]; //创建一个管道 fd[0]:读管道,fd[1]:写管道。 pipe(fd); while ((id=fork())==-1); if (id==0) { //将后边的字符串写到buf中 sprintf(buf,"Child1 is sending message!"); write(fd[1],buf,50); //立即终止调用进程 exit(0); } else { //在获得通知前该线程将一直等待 wait(0); read(fd[0],s,50); printf("%s\n",s); while ((pid=fork())==-1); if (pid==0){ sprintf(buf,"Child2 is sending message!"); write(fd[1],buf,50); exit(0); } else{ wait(0); read(fd[0],s,50); printf("%s\n",s); } } return 0; }
- 运行结果
3.消息队列通信
- 代码实现
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/msg.h> #include <sys/ipc.h> #define MSG_KEY 24 //消息队列标识符 int msqid; struct msgbuf{ // 消息类型 long mtype; // 缓冲区大小 char mtext[1024]; }msgbuf; void client(){ msqid=msgget(MSG_KEY,0666|IPC_CREAT); printf("Input a line:"); scanf("%s",msgbuf.mtext); msgbuf.mtype=1; //将消息输入到缓冲区中 msgsnd(msqid,&msgbuf,1024,0); } void server(){ msqid=msgget(MSG_KEY,IPC_CREAT|0666); //从缓冲区中取出消息 msgrcv(msqid,&msgbuf,1024,2L,0); printf("The reversed line is:%s\n",msgbuf.mtext); //删除消息队列 msgctl(msqid,IPC_RMID,0); } int main() { int p1; while((p1=fork())==-1); if (p1==0){ server(); wait(0); } else{ client(); } return 0; }
- 运行结果
4.共享区通信
暂未实现,有会的小伙伴可以在评论区留言。大家一起交流进步。
这篇关于操作系统实验——进程通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-0600-macOS和Linux安装和管理多个Python版本
- 2024-03-30[译]漫画SELinux概念
- 2024-03-29linux 移动文件
- 2024-03-28linux .so file
- 2024-03-28Linux 磁盘管理
- 2024-03-28Linux学习笔记(十三)磁盘管理(一):磁盘分区
- 2024-03-26linux 创建 文件
- 2024-03-25使用SecureCRT对Linux vim进行颜色设置
- 2024-03-202019-2020-12 20199317 《Linux内核原理与分析》 第十二周作业
- 2024-03-20Linux运维的第二周总结