//欢迎大家评论提出意见
#include"utili.h"
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/sem.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<string.h>
#include<sys/msg.h>
union semun
{
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
//.........ser.c
#include"utili.h"
int main()
{
key_t shm_key = ftok("myshm",0xff);
if(shm_key == -1)
{
perror("ftok shm_key");
exit(1);
}
//shmget函数 用于创建或打开一个共享内存
int shm_id = shmget(shm_key,1024,IPC_CREAT|0755);
if(shm_id == -1)
{
perror("shmget");
exit(1);
}
//void *shmat(int dhmid,int cmd,stuct dhmid_ds *buf);
//shmat 连接共享内存与某个进程的地址空间
void *shm_addr = shmat(shm_id,NULL,0);
if(shm_addr == (void*)-1)
{
perror("shmat");
shmctl(shm_id,IPC_RMID,NULL);
exit(1);
}
//加入信号量,实现通信
key_t sem_key = ftok("mysem",0xfe);
//semget -创建一个新信号量或者取得一个现有的信号量
int sem_id = semget(sem_key,2,IPC_CREAT|IPC_EXCL|0755);
union semun init_val;
init_val.val = 0;
semctl(sem_id,0,SETVAL,init_val);
semctl(sem_id,1,SETVAL,init_val);
struct sembuf p = {1,-1,0},
v = {0, 1,0};
while(1)
{
printf("Ser:>");
scanf("%s",(char*)shm_addr);
if(strcmp((char*)shm_addr,"quit") == 0)
{
// shmdt()-当进程完成某个共享内存区的使用时,调用此函数断接内存区
shmdt(shm_addr);
shmctl(shm_id,IPC_RMID,NULL);
break;
}
semop(sem_id,&v,1);//
semop(sem_id,&p,1);
printf("Cli:>%s\n",(char*)shm_addr);
}
return 0;
}
//..................cli.c
#include"utili.h"
int main()
{
key_t shm_key = ftok("myshm",0xff);
if(shm_key == -1)
{
perror("ftok shm_key");
exit(1);
}
//shm_id 用于创建或打开一个共享内存
int shm_id = shmget(shm_key,0,0);
if(shm_id == -1)
{
perror("shmget");
exit(1);
}
//shmat 断接内存区
void *shm_addr = shmat(shm_id,NULL,0);
if(shm_addr == (void*)-1);
{
perror("shmat");
// shmctl(shm_id,IPC_RMID,NULL);
exit(1);
}
//加入信号量,实现通信
key_t sem_key = ftok("myshm",0xfe);
int sem_id = semget(sem_key,0,0);
struct sembuf p = {1,-1,0},
v = {0,1,0};
while(1)
{
semop(sem_id,&p,1);
printf("Ser:>%s\n",(char*)shm_addr);
printf("Cli:>");
scanf("%s",(char*)shm_addr);
if(strcmp((char*)shm_addr,"quit") == 0)
{
shmdt(shm_addr);
//shmctl(shm_id,IPC_RMID,NULL);
break;
}
semop(sem_id,&v,1);
}
return 0;
}
进程通信方式--共享内存(shm)--实现自由通信
最新推荐文章于 2024-04-26 15:14:08 发布