c Shared Memory demo

A data writing process, a process of reading data

Writing process:

1. shmget () Gets Shared Memory

2. shmat () shared memory mapped into the process space

3. Write data

Reading process:

1. shmget () Gets Shared Memory

2. shmat () shared memory mapped into the process space

3. Read Data

4. shmdt () the shared memory space is released from the process map

5. shmctl () to delete the shared memory
reading process

//
// Created by gxf on 2020/2/10.
//

#ifndef UNTITLED_MAIN_H
#define UNTITLED_MAIN_H

char *ftokFilePath = "/Users/gxf/CLionProjects/untitled/main.c";
int project_id = 10;

typedef struct {
    int age;
    char name[50];
}person;

#endif //UNTITLED_MAIN_H
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

#include "main.h"


int main () {
    key_t ftokRes = ftok(ftokFilePath, project_id);
    person * zhangsan;
    person lisi = {10, "lisi"};

    int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT | 0777);
    printf("shamid :%d\n", shmid);
    zhangsan = (person *)shmat(shmid, NULL, SHM_W);
    zhangsan->age = 20;
    strcpy(zhangsan->name, "zhangsan1111");


    return 0;
}
//
// Created by gxf on 2020/2/10.
//
#include <stdlib.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

#include  "main.h"

int main () {
    key_t ftokRes = ftok(ftokFilePath, project_id);
    printf("%d\n", ftokRes);
    person *zhangsan = malloc(sizeof(person));
    int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT);
    person *shmaddr = shmat(shmid, NULL, SHM_R);
    memcpy(zhangsan, shmaddr, sizeof(person));
    printf("age:%d, name:%s\n", zhangsan->age, zhangsan->name);
    int res = shmdt(shmaddr);
    if (res)
        fprintf(stderr, "shmdt fail");
    res = shmctl(shmid, IPC_RMID, NULL);
    if (res)
        fprintf(stderr, "rm ipcs -m fail");


    return 0;
}

  

  

 

Guess you like

Origin www.cnblogs.com/luckygxf/p/12291505.html