44 lines
895 B
C
44 lines
895 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;
|
|
}
|
|
|
|
strcpy(buf, "hi, shared memory");
|
|
printf("write data ok\n");
|
|
|
|
/*
|
|
// 删除共享内存
|
|
int ret = shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
|
|
if (ret == -1)
|
|
{
|
|
perror("shmctl");
|
|
return 1;
|
|
}
|
|
printf("shared memory deleted\n");
|
|
*/
|
|
return 0;
|
|
} |