Linux进程间通信(共享存储区通信和管道通信)
Linux进程间通信(共享存储区通信和管道通信)
本周操作系统实验课要求写几个关于Linux下进程通信的小程序。实验要求如下:
第一个程序已在前篇文章中贴出,本文给出后两个。
使用共享存储区通信:
memserve.c:
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #define Key 3000
- int main(void)
- {
- int x, shmid;
- int *shmptr;
- if((shmid=shmget(Key, sizeof(int), IPC_CREAT|0666)) < 0)
- printf("shmget error"), exit(1);
- if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1)
- printf("shmat error"), exit(1);
- printf("Serve start: \n");
- while(1)
- {
- scanf("%d",shmptr);
- int i=*shmptr;
- while(i==*shmptr);
- printf("Client number: %d\n",*shmptr);
- }
- }
memclient.c:
[cpp]- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #define Key 3000
- int main(void)
- {
- int x, shmid;
- int *shmptr;
- if((shmid=shmget(Key, sizeof(int), 0666)) < 0)
- printf("shmget error"), exit(1);
- if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1) //第二个参数指定引入位置,0表示由内核决定引入位置
- printf("shmat error"), exit(1);
- printf("Client start:\n");
- while(1)
- {
- scanf("%d",shmptr);
- int i=*shmptr;
- while(i==*shmptr);
- printf("Serve number: %d\n",*shmptr);
- }
- }
先运行semserve.c,后运行semclient.c。以上程序虽然已经可以做到在服务器和客户端间轮流修改共享存储区值并显示结果,但是在启动服务器和客户端的时候必须先输入两个不相等的值!这只不过是非常简单的一种处理方式,希望高手给出更好的方式哈!(百度之后发现有人通过对 share memory做P()V()操作来解决这个问题!我自己还想了一种方式:可以通过创建一个struct Memory{ id,value} 。id中存放进程的标识,然后在后面while()中输出时,做判断。是对方的id则输出。)
运行结果如下:
|
评论暂时关闭