基础共享内存通信示例
以下示例展示生产者-消费者模型,使用共享内存传递数据:
生产者程序(producer.c)
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#define SHM_KEY 0x1234
#define SHM_SIZE 1024
int main() {
int shmid = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
return 1;
}
char *shm_ptr = (char*)shmat(shmid, NULL, 0);
if (shm_ptr == (void*)-1) {
perror("shmat");
return 1;
}
strcpy(shm_ptr, "Hello from producer!");
printf("Producer wrote: %s\n", shm_ptr);
shmdt(shm_ptr);
return 0;
}
消费者程序(consumer.c)
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHM_KEY 0x1234
#define SHM_SIZE 1024
int main() {
int shmid = shmget(SHM_KEY, SHM_SIZE, 0666);
if (shmid == -1) {
perror("shmget");
return 1;
}
char *shm_ptr = (char*)shmat(shmid, NULL, 0);
if (shm_ptr == (void*)-1) {
perror("shmat");
return 1;
}
printf("Consumer read: %s\n", shm_ptr);
shmdt(shm_ptr);
shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
return 0;
}
编译与运行
# 编译
gcc producer.c -o producer
gcc consumer.c -o consumer
# 运行生产者
./producer
# 输出: Producer wrote: Hello from producer!
# 运行消费者
./consumer
# 输出: Consumer read: Hello from producer!
(通过 ipcs -m
查看共享内存)