Linux 的system v ipc是进程间通信的重要工具。
使用共享内存的基本步骤:
1、用ftok产生 key_t变量
2、用shmget创建共享内存
3、用shmat映射共享内存
4、之后是共享内存的操作,直接操作映射的变量地址
int shmgat(key_t key, int size, int shmflag);
key:上一步产生的key_t变量
size:创建共享内存的大小
shmflag:创建时的参数
成功返回共享内存的id 失败返回-1
void *shmat(int shmid, const void *shmaddr, int shmflg)
shmid:上一步产生的共享内存id
shmaddr:真实内存中的地址,一般写NULL让系统自动分配
shmflg:打开标志SHM_REONLY只读, 0 读写
例子:
输入数据方:
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main(void)
{
key_t key;
key = ftok(".",101);
int shmid;
// shmid = shmget(key, 1024, IPC_CREAT);
if((shmid = shmget(key, 1024, IPC_CREAT)) == -1)
{
printf("shmget error\n");
exit(1);
}
void *a;
if((a = shmat(shmid, NULL, 0)) == (void *)-1)
{
printf("shmat error\n");
exit(1);
}
while(1)
fgets((char*)a, 1024, stdin );
return 0;
}
接收数据方:
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main(void)
{
key_t key;
key = ftok(".",101);
int shmid;
if(shmid = shmget(key, 1024, IPC_CREAT) == -1)
{
printf("shmget error\n");
exit(1);
}
void *b;
if((b = shmat(shmid, NULL, 0)) == (void *)-1)
{
printf("shmat error\n");
exit(1);
}
while(1)
{
if(*((char*) b) != '\0')
{
printf("%s", (char *)b);
bzero(b,1024);
}
}
return 0;
}
两个文件放在同一目录下运行。
我注意到有些奇怪的一点,就是创建共享内存的时候似乎必须加入判断语句,如果不加入,会产生段错误。即使说加入的判断内容完全没有执行也必须加入判断,如发送方代码中注释掉的那一行,如果注释符号删除,并把下面的整个if语句注释掉,没有经过判断的话无论结果如何程序都会出现段错误。
至于其他的shmdt()(取消映射)和shmctl()(设置共享内存),也是比较有用的。
其他函数参数可看百度百科