Linux下C++共享內存


記錄一下。

send.cpp:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
 
#define BUFSZ 1024*1024
 
int main(int argc, char *argv[])
{
    int shmid;
    int ret;
    key_t key;
    char *shmadd;
    
    //創建key值
    key = ftok(".", 2016);
    
    //創建共享內存
    shmid = shmget(key, BUFSZ, IPC_CREAT|0666);    
    
    //映射
    shmadd = (char*)shmat(shmid, NULL, 0);

    //拷貝數據至共享內存區
    printf("copy data to shared-memory\n");
    bzero(shmadd, BUFSZ); // 共享內存清空
    strcpy(shmadd, "how are you, lh");
    
    return 0;
}

rev.cpp:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
 
#define BUFSZ 1024*1024
 
int main(int argc, char *argv[])
{
    int shmid;
    int ret;
    key_t key;
    char *shmadd;
    
    //創建key值
    key = ftok(".", 2016);
    
    //打開共享內存
    shmid = shmget(key, BUFSZ, IPC_CREAT|0666);

    //映射
    shmadd = (char*)shmat(shmid, NULL, 0);

    //讀共享內存區數據
    printf("data = [%s]\n", shmadd);
    
    //分離共享內存和當前進程
    ret = shmdt(shmadd);

    //刪除共享內存
  //  shmctl(shmid, IPC_RMID, NULL);
        
    return 0;
}

如果共享內存shmid已存在,可以用ipcs查看,然后ipcrm -m shmid刪除即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM