qfedu-linux-advanced-level/day5/shm5.c

47 lines
1.1 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 共享内存
#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);
// 删除共享内存
// NULL 表示不关心共享内存的信息
// int ret = shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
// 如果不写 NULL应该写一个结构体表示共享内存的信息
struct shmid_ds ds;
int ret = shmctl(shmid, IPC_RMID, &ds); // 删除共享内存
if (ret == -1)
{
perror("shmctl");
return 1;
}
printf("shared memory deleted\n");
return 0;
}