42 lines
870 B
C
42 lines
870 B
C
|
// 共享内存
|
||
|
#include <sys/shm.h>
|
||
|
#include <stdio.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
// 共享内存读数据
|
||
|
int main()
|
||
|
{
|
||
|
key_t key = ftok("/", 28);
|
||
|
|
||
|
// 获取共享内存的标识
|
||
|
int shmid = shmget(key, 32, IPC_CREAT | 0666);
|
||
|
if (shmid == -1)
|
||
|
{
|
||
|
perror("shmget");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
printf("shmid=%d\n", shmid);
|
||
|
|
||
|
// 获取共享内存的首地址
|
||
|
char *buf = shmat(shmid, NULL, 0); // NULL表示让系统自动分配共享内存的首地址
|
||
|
if (buf == (char *)-1)
|
||
|
{
|
||
|
perror("shmat");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
printf("共享内存的数据:%s\n", buf);
|
||
|
/*
|
||
|
// 删除共享内存
|
||
|
int ret = shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
|
||
|
if (ret == -1)
|
||
|
{
|
||
|
perror("shmctl");
|
||
|
return 1;
|
||
|
}
|
||
|
printf("shared memory deleted\n");
|
||
|
*/
|
||
|
return 0;
|
||
|
}
|