1、共享内存:两个进程在内存的同一块区域具备管理的权限,同时可以对内存进行读写操作,但是由于这样很难做到同步,所以要配合一些其他控制进程的,例如信号量
2、共享内存的函数:
int shmget(key_t key, size_t size, int shmflg); 创建共享内存
void *shmat(int shmid, const void *shmaddr, int shmflg); 挂接共享内存
int shmdt(const void *shmaddr); 关联共享内存
int shmctl(int shmid, int cmd, struct shmid_ds *buf); 销毁共享内存
3、实例
shma文件
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/shm.h>
#include<unistd.h>
#include<assert.h>
#include"sem.h"
int main()
{
sem_init();
int shmid = shmget((key_t)1234,256,IPC_CREAT|0600);
assert(shmid != -1);
char *s = (char*)shmat(shmid,NULL,0);
while(1)
{
char buff[128] = {0};
printf("input\n");
fgets(buff,128,stdin);
strcpy(s,buff);
if(strncmp(buff,"end",3)==0)
{
break;
}
sem_v();
}
shmdt(s);
exit(0);
}
shmb文件:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/shm.h>
#include<unistd.h>
#include<assert.h>
#include"sem.h"
int main()
{
sem_init();
int shmid = shmget((key_t)1234,256,IPC_CREAT|0600);
assert(shmid != -1);
char *p = (char*)shmat(shmid,NULL,0);
while(1)
{
sem_p();
if(strncmp(p,"end",3)==0)
{
break;
}
printf("p=%s\n",p);
}
shmdt(p);
sem_destroy();
shmctl(shmid,IPC_RMID,NULL);
exit(0);
}