一.定义:
它允许两个不相关的进程访问同一段逻辑内存。共享内存是两个正在运行的进程之间传递数据的一种非常有效的方式。虽然X/Open标准并没有对它做出要求,但大多数共享内存的具体实现,都把由不同进程之间共享的内存安排为同一段物理内存。
二.共享内存使用机制:
1.shmget函数:
(1)定义:通过shmget函数来创建共享内存。
(2)原型:
int shmget(key_t key, size_t size, int shmflg);
2.shmat函数:
(1)定义:第一次创建共享内存时,它不能被任何进程访问。要想启动对该共享内存的访问,必须将其连接到一个进程的地址空间。
(2)原型:
void shmat(int shm_id, const void *shm_addr, int shmflg);
3.shmdt函数:
(1)定义:将共享内存从当前的进程中分离。
(2)原型:
void shmdt(const void *shm_addr);
4.shmctl函数:
(1)定义:与复杂的信号量函数相比,共享内存的控制函数稍微简单。
(2)原型:
int shmctl(int shm_id, int command, struct shmid_ds *buf);
三.例子:
分为3部分,shm1.c作为消费者,shm2.c作为生产者,和shm_com.h作为公共头文件。
1.shm_com.h:
#define TEXT_SIZE 2048
struct shared_use_st {
int written_by_you;
char some_text[TEXT_SIZE];
};
2.shm1.c:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
int main() {
int running = 1;
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
int shmid;
srand((unsigned int)getpid());
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff->written_by_you = 0;
while (running) {
if (shared_stuff->written_by_you) {
printf("You wrote %s", shared_stuff->some_text);
sleep(rand() % 4);
shared_stuff->written_by_you = 0;
if (strncmp(shared_stuff->some_text, "end", 3) == 0) {
running = 0;
}
}
}
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
3.shm2.c:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
int main() {
int running = 1;
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
char buffer[BUFSIZ];
int shmid;
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
while (running) {
while (shared_stuff->written_by_you == 1) {
sleep(1);
printf("waiting for client.\n");
}
printf("Enter some text.\n");
fgets(buffer, BUFSIZ, stdin);
strncpy(shared_stuff->some_text, buffer, TEXT_SIZE);
shared_stuff->written_by_you = 1;
if (strncmp(buffer, "end", 3) == 0) {
running = 0;
}
}
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}