标签:共享内存
共享内存 ---- 数据传递 --- 最高效 ,但 不提供 同步和互斥 --- 和 信号量 搭配使用
头文件:#include<sys/ipc.h>
#include<sys/shm.h>
attch(挂接) nattach(有n个进程挂接到共享内存上) ... ...
void *shmat(int shmid, const void *shmaddr, int shmflg);//挂接
int shmdt(const void *shmaddr);//关联
实例:
//comm.h
#pragma once #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> #include<sys/wait.h> #include<errno.h> #define _PATH_ ‘.‘ #define _PROJ_ID_ 0x6666 #define _SIZE_ 4096 int get_shm(); void *at_shm(int shm_id); int dt_shm(void *addr); int destroy_shm(int _shm_id);
//comm.c
#include "comm.h"
int get_shm()
{
key_t _key=ftok((char*)_PATH_,_PROJ_ID_);
int flags=IPC_CREAT|0666;
if(_key < 0)
{
perror("ftok");
return -1;
}
int shm_id=-1;
if((shm_id = shmget(_key,_SIZE_,flags)) < 0)
{
perror("shmget");
return -1;
}
return shm_id;
}
void *at_shm(int shm_id)
{
return shmat(shm_id,NULL,0);
}
int dt_shm(void *addr)
{
return shmdt(addr);
}
int destroy_shm(int _shm_id)
{
if(shmctl(_shm_id,IPC_RMID,NULL) < 0)
{
perror("shmctl");
return -1;
}
return 0;
}//shm_server.c
#include "comm.h"
int main()
{
int shm_id=get_shm();
char *start=at_shm(shm_id);
int i=0;
for(i=0;i<_SIZE_;++i)
{
printf("%s\n",start);
start[i]=‘A‘;
start[i+1]=‘\0‘;
sleep(1);
}
dt_shm(start);
destroy_shm(shm_id);
return 0;
}//shm_client.c
#include "comm.h"
int main()
{
int shm_id=get_shm();
sleep(5);
char *start=at_shm(shm_id);
printf("%s",start);
dt_shm(start);
destroy_shm(shm_id);
return 0;
}运行结果:
结合进程:
//shm.c
#include "comm.h"
int main()//shm.c
{
int shm_id = get_shm();
pid_t id = fork();
if(id < 0)
{
printf("fork error\n");
return -1;
}else if(id == 0)//child
{
char *buf = at_shm(shm_id);
int i = 0;
while(i++ < _SIZE_)
{
printf("%s",buf);
buf[i]=‘A‘;
buf[i+1]=‘\0‘;
sleep(1);
}
dt_shm(buf);
}
else//father
{
char *buf = at_shm(shm_id);
sleep(5);
printf("%s\n", buf);
dt_shm(buf);
waitpid(id, NULL, 0);
destroy_shm((char)shm_id);
}
return 0;
}本文出自 “花开彼岸” 博客,请务必保留此出处http://zxtong.blog.51cto.com/10697148/1764724
标签:共享内存
原文地址:http://zxtong.blog.51cto.com/10697148/1764724