Usage simple of shared memory

本文介绍了一种使用C++实现进程间通信的方法——共享内存。详细展示了如何创建、写入、读取、检查及删除共享内存段,并提供了完整的代码示例。

 

-- create a shared memory

#: cat create.C

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>

using namespace std;

int main()
{
    int shmid;
    key_t key=0x1234;

    //if((shmid=shmget(key,32,0666|IPC_CREAT|IPC_EXCL)) < 0)
    if((shmid=shmget(key,32,0666|IPC_CREAT)) < 0)
    {
        printf("shmid failed. Exit/n");
        exit(1);
    }
    else
        printf("shmid succes id=%d/n",shmid);

}

 

-- Write into shared memory --

#: cat write.C
#include <iostream>

#include <sys/ipc.h>
#include <sys/shm.h>

#include "Amsg.h"

using namespace std;

int main()
{
    int shmid=SHMID;
    char *shmaddress;

    shmaddress=(char *)shmat(shmid,NULL,0);
    if((int)shmaddress == -1)
    {
            printf("shmat failed. Exit/n");
            exit(3);
    }
    else
    {
            printf("shmat success return 0x%x/n",shmaddress);
    }


    Amsg * msg = new (shmaddress) Amsg();
    if (msg != NULL)
    {
            printf("new Amsg object was created at 0x%x/n",msg);
            msg->setName(1,(char*)"I am boy!/n");
    }

    if((shmdt(shmaddress)) < 0)
          printf("shmdt failed. Exit/n");

}

 

-- Check shared memory --

#: cat info.C

#include <iostream>

#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    int shmid=SHMID;
    struct shmid_ds dsbuf;

    if((shmctl(shmid,IPC_STAT,&dsbuf))<0)
    {
             printf("shmctl failed. Exit/n");
             exit(4);
    }

    printf("shmctl, shared memory creater: %d/n",dsbuf.shm_cpid);
    printf("shmctl, shared memory size: %d/n",dsbuf.shm_segsz);
    printf("shmctl, shared memory last access: %d/n",dsbuf.shm_lpid);
}

 

#

# 'ipcs -am' can list out all shared memory

#

 

-- Read out from shared memory --

#: write.C

#include <iostream>

#include <sys/ipc.h>
#include <sys/shm.h>

#include "Amsg.h"

using namespace std;

int main()
{
    int shmid=SHMID;
    char *shmaddress;
    struct shmid_ds dsbuf;
   
   
    if((shmaddress=(char *)shmat(shmid,0,0))<0)
    {
            printf("shmat faild. Exit/n");
            exit(5);
    }

    Amsg * msg = reinterpret_cast<Amsg *>(shmaddress);
    char * output = msg->getName(1);

    printf("Read out from shared memory: %s/n",output);
    if((shmdt(shmaddress)) < 0)
             printf("shmdt failed. Exit/n");
}

 

-- Delete shared memory --

#: cat delete.C

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    int shmid=SHMID;

    if(shmctl(shmid,IPC_RMID,NULL) < 0)
    {
            printf("shmctl failed. Exit/n");
            exit(7);
    }
}

 

#

# 'ipcrm -m $id' can remove shared memory identified by $id.

#

 

-- appendix --

#: Amsg.h

class Amsg
{
public:
        Amsg() {}
public:
        void setName(int i, char *name)
        {
                this->id = i;
                strncpy(this->value,name,20);
        }

        char * getName(int i)
        {
                if (i==this->id)
                        return this->value;
                else
                        return (char *)"NULL";
        }
public:
        int id;
        char value[20];
};

 

-- appendix --

#: cat Makefile


CC = .../bin/CC

all: create info write read delete

create : create.o
        CC -o $@ $^

SHMID = $(shell ./create | awk -F/= '{print $$2}')

info: info.o
        CC -o $@ -DSHMID=$(SHMID) $^
write: write.o
        CC -o $@ -DSHMID=$(SHMID) $^
read: read.o
        CC -o $@ -DSHMID=$(SHMID) $^
delete: delete.o
        CC -o $@ -DSHMID=$(SHMID) $^

%.o: %.C
        CC -c -o $@ -DSHMID=$(SHMID) $^

.PHONY:clean

clean:
        rm -rf *.o a.out create info write read delete

 

[root@node1 tmp]# perf --help usage: perf [--version] [--help] [OPTIONS] COMMAND [ARGS] The most commonly used perf commands are: annotate Read perf.data (created by perf record) and display annotated code archive Create archive with object files with build-ids found in perf.data file bench General framework for benchmark suites buildid-cache Manage build-id cache. buildid-list List the buildids in a perf.data file c2c Shared Data C2C/HITM Analyzer. config Get and set variables in a configuration file. data Data file related processing diff Read perf.data files and display the differential profile evlist List the event names in a perf.data file ftrace simple wrapper for kernel's ftrace functionality inject Filter to augment the events stream with additional information kallsyms Searches running kernel for symbols kmem Tool to trace/measure kernel memory properties kvm Tool to trace/measure kvm guest os list List all symbolic event types lock Analyze lock events mem Profile memory accesses record Run a command and record its profile into perf.data report Read perf.data (created by perf record) and display the profile sched Tool to trace/measure scheduler properties (latencies) script Read perf.data (created by perf record) and display trace output stat Run a command and gather performance counter statistics test Runs sanity tests. timechart Tool to visualize total system behavior during a workload top System profiling tool. version display the version of perf binary probe Define new dynamic tracepoints trace strace inspired tool 翻译和解释含义
08-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值