目录
1. A进程写入一个整型,在该整型后,写入一个字符串
2. B进程将共享内存中的整型以及字符串读取出来;
代码:
A进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建key值
key_t key = ftok("./", 1);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#x\n", key);
//创建共享内存
int shmid = shmget(key, 32, IPC_CREAT|0664);
if(shmid < 0)
{
perror("shmget");
return -1;
}
printf("shmid = %d\n", shmid);
//共享内存的映射
void* shmaddr = shmat(shmid, NULL, 0);
int *a = (int *)shmaddr;
*a = 10;
char *str = (char *)(a+1);
strcpy(str,"hello world");
system("ipcs -m");
return 0;
}
执行结果:
B进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建key值
key_t key = ftok("./", 1);
if(key < 0)
{