代码示例_IPC_共享内存

共享内存

 


1.头文件

#ifndef __SHM_H__
#define __SHM_H__


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>


key_t Get_Key(void);
int Shm_Creat(key_t key, size_t size);
void *Shm_At(int shmid);
int Shm_Dt(const void *shmaddr);
int Shm_Del(int shmid);



#endif

2.msg.c

#include"shm.h"


//获取key
key_t Get_Key(void)
{
    key_t key =ftok("/",0x66);
    if(key <0){
        perror("Get_Key ftok failed");
        exit(1);
    }
    return key;
}

//创建获取
int Shm_Creat(key_t key, size_t size)
{
    int shmid =shmget(key, size, 0666|IPC_CREAT);
    if(shmid < 0){
        perror("Shm_Creat shmget failed ");
        exit(1);
    }
    return shmid;
}

//挂载
void *Shm_At(int shmid)
{
    char *shmat_rel =shmat(shmid,NULL,0);
    if(shmat_rel < 0){
        perror("Shm_At shmat failed ");
        exit(1);
    }
    return shmat_rel;
}

//卸载
int Shm_Dt(const void *shmaddr)
{
    int shmdt_rel =shmdt(shmaddr);
    if(shmdt_rel < 0){
        perror("Shm_Dt shmdt failed ");
        exit(1);
    }
    return shmdt_rel;
}

//删除
int Shm_Del(int shmid)
{
    int shmctl_rel =shmctl(shmid, IPC_RMID, NULL);
    if(shmctl_rel < 0){
        perror("Shm_Del shmctl failed ");
        exit(1);
    }
    return shmctl_rel;
}

3.client

#include "shm.h"

int main(void)
{
    key_t key =Get_Key();
    int shmid =Shm_Creat(key,1024);
    char *shmat_add =Shm_At(shmid);
    while(1){       //to read
        fgets(shmat_add, 1024, stdin);
        if(strncmp(shmat_add, "quit", 4) ==0)
            break;
    }
    Shm_Dt(shmat_add);
    Shm_Del(shmid);

    return 0;
}

4.server

#include "shm.h"

int main(void)
{
    key_t key =Get_Key();
    int shmid =Shm_Creat(key,1024);
    char *shmat_add =Shm_At(shmid);
    while(1){       //to write
        sleep(1);
        fputs(shmat_add, stdout);
        if(strncmp(shmat_add, "quit", 4) ==0)
            break;
    }
    Shm_Dt(shmat_add);
    Shm_Del(shmid);

    return 0; 
}


success !

Stay hungry, stay foolish 待续。。。
原文地址:https://www.cnblogs.com/panda-w/p/11049407.html