共享内存实验
时间: 2023-08-17 13:05:59 浏览: 67
共享内存是一种进程间通信的方式,它允许多个进程访问同一块物理内存。在共享内存中,多个进程可以通过读写同一块内存来实现数据的共享。
下面是一个简单的共享内存实验,包括创建和使用共享内存的过程。在 Linux 环境下,可以使用 System V IPC(Inter-Process Communication)机制来实现共享内存。
1. 创建共享内存
使用 `shmget` 函数创建一个共享内存段。该函数需要传入三个参数:共享内存键值、共享内存大小和标志。如果共享内存创建成功,函数将返回共享内存标识符。
```c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHM_SIZE 1024
int main() {
int shmid;
key_t key = 1234;
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
return -1;
}
printf("Shared memory segment created with ID %d\n", shmid);
return 0;
}
```
2. 连接共享内存
使用 `shmat` 函数将共享内存附加到当前进程的地址空间。该函数需要传入两个参数:共享内存标识符和附加的地址。如果共享内存附加成功,函数将返回共享内存的起始地址。
```c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHM_SIZE 1024
int main() {
int shmid;
key_t key = 1234;
char *shmaddr;
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
return -1;
}
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
return -1;
}
printf("Shared memory attached at address %p\n", shmaddr);
return 0;
}
```
3. 写入共享内存
使用指针操作共享内存,将数据写入共享内存中。
```c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#define SHM_SIZE 1024
int main() {
int shmid;
key_t key = 1234;
char *shmaddr;
char *message = "Hello, shared memory!";
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
return -1;
}
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
return -1;
}
memcpy(shmaddr, message, strlen(message) + 1);
printf("Message written to shared memory: %s\n", shmaddr);
return 0;
}
```
4. 读取共享内存
使用指针操作共享内存,将数据从共享内存中读取出来。
```c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#define SHM_SIZE 1024
int main() {
int shmid;
key_t key = 1234;
char *shmaddr;
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
return -1;
}
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
return -1;
}
printf("Message read from shared memory: %s\n", shmaddr);
return 0;
}
```
这样,我们就完成了一个简单的共享内存实验。需要注意的是,共享内存需要进行进程同步和互斥,以避免数据访问冲突。在实际应用中,需要考虑更复杂的情况。