方式1 使用mmap
#include <sys/mman.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
void perror(const char *s);
void* create_shm(int size) {
int protection = PROT_READ | PROT_WRITE;
int visibility = MAP_ANONYMOUS | MAP_SHARED;
return mmap(NULL, size, protection, visibility, 0, 0);
}
int main() {
char* msg1 = "heheheheh";
char* msg2 = "xxxxoxoxoxox";
printf("size of msg2: %d\n", strlen(msg2));
void* shm = create_shm(12);
memcpy(shm, msg1, strlen(msg1));
int pid = fork();
if (pid < 0) {
perror("fork faild");
}
if (pid == 0) {
printf("entry child process...\n");
printf("child process read message from shared memory: %s\n", shm);
memcpy(shm, msg2, strlen(msg2));
printf("child process write message to shared memory: %s\n", msg2);
} else {
printf("this is parent process\n");
printf("parent process read message: %s\n", shm);
sleep(1);
printf("after 1 second parent process read: %s\n", shm);
}
}
方法2 使用shmget
程序1 创建共享内存,并写入数据,程序2 获取共享内存,然后读取内容。
- 程序1
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
// shmkey usually defined by ftok, 2222 here is jusk simplify
int shmkey = 2222;
int main() {
// create shared memory
int shmid = shmget(shmkey, 1024, IPC_CREAT | 0777);
if (shmid < 0) {
perror("shmget faild");
exit(1);
}
// attach the shared memory
void* shm = shmat(shmid, NULL, 0);
char* message = "hello world";
printf("write message to shared message: %s\n", message);
memcpy(shm, message, strlen(message));
// wait another process to read shared memory
int wait = 30;
while (1) {
sleep(1);
wait--;
if (wait < 0) {
// delete shared memory and exit
printf("it's time to say good bye...\n");
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
}
}
- 程序2
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
// shmkey usually defined by ftok, 2222 here is jusk simplify
int shmkey = 2222;
int main() {
// create shared memory
int shmid = shmget(shmkey, 1024, 0777);
if (shmid < 0) {
perror("shmget faild");
exit(1);
}
// attach the shared memory
void* shm = shmat(shmid, NULL, 0);
printf("read message to shared message: %s\n", shm);
shmdt(shm);
}