共享内存
#include <sys/ipc.h>
#include <sys/shm.h>
通过程序建立了一个共享内存
# ipcs -m 建立并且存放了数据
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x74006dfa 2293760 root 600 4 0
0x00000000 2654209 root 644 80 2
0x74006df9 2260994 root 600 4 0
0x00000000 2686979 root 644 16384 2
0x00000000 2719748 root 644 280 2
0x000003e8 2949125 root 666 512 0
# ipcs -m 读取清除之后
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x74006dfa 2293760 root 600 4 0
0x00000000 2654209 root 644 80 2
0x74006df9 2260994 root 600 4 0
0x00000000 2686979 root 644 16384 2
0x00000000 2719748 root 644 280 2
程序举例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_KEY 1000L
#define SHM_SIZ 512
#define BUF_SIZ 50
int main() {
pid_t pid;
int shmid;
if ((shmid = shmget(SHM_KEY, SHM_SIZ, IPC_CREAT | 0666)) < 0) {
perror("shmget error");
exit(0);
}
printf("shared memory id = %d\n", shmid);
if ((pid = fork() < 0)) {
perror("fork error");
}
if (pid == 0) {
char *address = shmat(shmid, NULL, 0);
if (address == NULL) {
perror("attatch error");
}
strcpy(address, "this is a shared momery test!");
shmdt(address);
sleep(1);
}
char *address = shmat(shmid, NULL, 0);
if (address == NULL) {
perror("attatch error");
}
printf("read data :%s\n", address);
shmdt(address);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
运行结果:
shared memory id = 2949125
read data :this is a shared momery test!
运行 FINISHED; Segmentation fault; 实时: 1s; 用户: 0ms; 系统: 0ms