• [国嵌攻略][085][共享内存通讯]


    共享内存

    共享内存是IPC机制中的一种,它允许两个相关的进程访问同一段内存,这是传递数据的一种有效的方式。

    A.c

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 2048
    
    typedef struct sharemem{
        int  flag;         //共享标志
        char data[SIZE];   //共享数据
    }ShareMem;
    
    void main(){
        //创建共享内存
        int key;
        int shmid;
        
        key = ftok("./", 0);
        shmid = shmget(key, sizeof(ShareMem), IPC_CREAT);
        
        //映射共享内存
        ShareMem *shareMem;
        
        shareMem = (ShareMem *)shmat(shmid, NULL, 0);
    
        //设置共享内存
        shareMem->flag = 0;
    
        while(1){
            //判断共享标志
            while(shareMem->flag != 0);
            
            //获取用户输入
            char buffer[SIZE];
            
            fgets(buffer, SIZE, stdin);
            
            //写入共享内存
            strncpy(shareMem->data, buffer, SIZE);
            shareMem->flag = 1;
            
            //判断是否退出
            if(strncmp(buffer, "quit", 4) == 0){
                break;
            }
        }
        
        //脱离共享内存
        shmdt((const void *)shareMem);
    }

    B.c

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 2048
    
    typedef struct sharemem{
        int  flag;         //共享标志
        char data[SIZE];   //共享数据
    }ShareMem;
    
    void main(){
        //打开共享内存
        int key;
        int shmid;
        
        key = ftok("./", 0);
        shmid = shmget(key, sizeof(ShareMem), IPC_CREAT);
        
        //映射共享内存
        ShareMem *shareMem;
        
        shareMem = (ShareMem *)shmat(shmid, NULL, 0);
        
        //设置共享内存
        shareMem->flag = 1;
        
        while(1){
            //判断共享标志
            while(shareMem->flag != 1);
            
            //读取共享内存
            char buffer[SIZE];
            
            strncpy(buffer, shareMem->data, SIZE);
            shareMem->flag = 0;
            
            //显示共享内存
            printf("%s", buffer);
            
            //判断是否退出
            if(strncmp(buffer, "quit", 4) == 0){
                break;
            }
        }
        
        //脱离共享内存
        shmdt((const void *)shareMem);
        
        //删除共享内存
        shmctl(shmid, IPC_RMID, NULL);
    }
  • 相关阅读:
    973. K Closest Points to Origin
    919. Complete Binary Tree Inserter
    993. Cousins in Binary Tree
    20. Valid Parentheses
    141. Linked List Cycle
    912. Sort an Array
    各种排序方法总结
    509. Fibonacci Number
    374. Guess Number Higher or Lower
    238. Product of Array Except Self java solutions
  • 原文地址:https://www.cnblogs.com/d442130165/p/5226824.html
Copyright © 2020-2023  润新知