进程间通信
共享内存:
是被多个进程共享的一部分物理内存.共享内存是进程间共享数据的一种最快的方法,一个进程向共享内存区域写入了数据,共享这个内存区域的所有进程就可以立刻看到其中的内容.
进程1:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>
#define SHMKEY 1234
#define SHMSIZE 4096
int main()
{
int shmid;
int count = 0;
void *shmaddr;
shmid = shmget(SHMKEY, SHMSIZE,IPC_CREAT| IPC_EXCL);//创建共享内存
if(shmid == -1)
{
perror("shmget");
exit(1);
}
shmaddr = shmat(shmid, NULL, 0);//映射到虚拟地址空间
if(NULL == shmaddr)
{
perror("shmat");
exit(1);
}
*(int *)shmaddr = count; //数据写到共享内存
while(1)
{
count = *(int *)shmaddr;//读取数据
if(count >= 100)
{
break;
}
printf("Process A:count = %d\n",count);
count++;
*(int *)shmaddr = count; //数据写回到内存
usleep(100000);
}
shmdt(shmaddr);
shmctl(shmid, IPC_RMID, NULL );
return 0;
}
进程2:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>
#define SHMKEY 1234
#define SHMSIZE 4096
int main()
{
int shmid;
int count = 0;
void *shmaddr;
shmid = shmget(SHMKEY, SHMSIZE,0);//创建共享内存
if(shmid == -1)
{
perror("shmget");
exit(1);
}
shmaddr = shmat(shmid, NULL, 0);//映射到虚拟地址空间
if(NULL == shmaddr)
{
perror("shmat");
exit(1);
}
while(1)
{
count = *(int *)shmaddr;//读取数据
if(count >= 100)
{
break;
}
printf("Process B:count = %d\n",count);
count++;
*(int *)shmaddr = count;
unsleep(100000);
}
shmdt(shmaddr);
return 0;
}