这是一组能完成两个进程间的基础通讯的程序,基本功能为服务器建立链表储存数据,使用客户端来查找相关信息。
自定义头文件:
#ifndef COM_STHHH
#define COM_STHHH
#define KEYS_SHM 145644645
struct shm_struct {
int val;
char name[16];
int age;
int rw_num;
int t_num;
};
struct stu {
int val;
char name[16];
int age;
struct stu *next;
};
#endif
虚拟客户端程序:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include "comstruct.h"
struct shm_struct *ptshm=NULL;
int main()
{
int shmid=shmget(KEYS_SHM,sizeof(*ptshm),0666|IPC_CREAT);
if(shmid==-1){
perror("客户端建立出错");
return -1;
}
ptshm=shmat(shmid,NULL,0);
if(ptshm==(void*)-1){
perror("客户端映射出错");
return -1;
}
int i=1;
char aa[16];
while(i<10){
if(ptshm->rw_num==1 && ptshm->t_num==0){
if(strcmp(aa,ptshm->name)==0){
printf("客户端收到学生val:%d name:%s age:%d\n",\
ptshm->val,ptshm->name,ptshm->age);
}else{
printf("未找到学生%s\n",aa);
}
ptshm->t_num=1;
sleep(1);
}
if(ptshm->rw_num==1 && ptshm->t_num==1){
printf("客户端搜索:");
scanf("%s",ptshm->name);
strcpy(aa,ptshm->name);
ptshm->rw_num=0;
printf("客户端发出成功\n");
i++;
sleep(1);
}
}
int ret=shmdt(ptshm);
if(ret<0){
perror("客户端断开映射出错");
return -1;
}
ret=shmctl(shmid,IPC_RMID,NULL);
if(ret<0){
perror("客户端删除出错");
return -1;
}
return 0;
}
虚拟服务器程序,以链表形式建立数据库:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include "comstruct.h"
struct shm_struct *ptshm=NULL;
struct stu head;
struct stu *phead=&head;
int student_init(struct stu *pphead)
{
struct stu *ptail=pphead;
printf("请输入对应的val name age\n");
for(int i=1;i<=10;i++){
struct stu *p=malloc(sizeof(*p));
memset(p,0,sizeof(*p));
p->next=NULL;
printf("第%d个学生:",i);
scanf("%d%s%d",&p->val,p->name,&p->age);
if(p->name=="#" || p->age==0){
printf("输入结束\n");
free(p);
return 0;
}
ptail->next=p;
ptail=ptail->next;
}
}
int find_stu(struct stu *pphead,struct shm_struct *pptshm)
{
pphead=pphead->next;
while(pphead!=NULL && pptshm->name!=NULL){
if(strcmp(pptshm->name,pphead->name)==0){
pptshm->val=pphead->val;
strcpy(pptshm->name,pphead->name);
pptshm->age=pphead->age;
return 0;
}
pphead=pphead->next;
}
strcpy(pptshm->name,"no students");
return -1;
}
int main()
{
int shmid=shmget(KEYS_SHM,sizeof(*ptshm), 0666|IPC_CREAT);
if(shmid == -1){
perror("服务器建立出错");
return -1;
}
ptshm=shmat(shmid,NULL,0);
if(ptshm==(void*)-1){
perror("服务器映射出错");
return -1;
}
ptshm->rw_num=1;
ptshm->t_num=1;
student_init(phead);
int j=1;
while(j<10){
if(ptshm->rw_num==0 && ptshm->t_num==0){
int ret_num=find_stu(phead,ptshm);
if(ret_num==0) {printf("服务器发送成功\n");}
else {printf("未找到对应学生\n");}
ptshm->rw_num=1;
sleep(1);
j++;
}
if(ptshm->rw_num==0 && ptshm->t_num==1){
printf("服务器收到name:%s \n",ptshm->name);
ptshm->t_num=0;
sleep(1);
}
}
int ret=shmdt(ptshm);
if(ret<0){
perror("服务器断开映射出错");
return -1;
}
ret=shmctl(shmid,IPC_RMID,NULL);
if(ret<0){
perror("服务器删除出错");
return -1;
}
return 0;
}