共享内存

15 篇文章 0 订阅

方式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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值