目前位置:我的異常網» C++ » linux上c++通過使用動态庫達到共享記憶體,該如何處理
linux上c++通過使用動态庫達到共享記憶體,該如何處理
www.myexceptions.net 網友分享于:2013-03-29 浏覽:42次
linux上c++通過使用動态庫達到共享記憶體
在linux上用C++生成的動态庫,達到共享記憶體是否可行?就是兩個獨立程式調用同一個動态庫,一個讀動态庫中的變量,一個寫動态庫的變量,來達到将一個程式的值傳到另一個程式
如動态庫程式
libtest.h
------------------------------------
#ifndef __LIBTEST_H__
#define __LIBTEST_H__
//設定值
bool my_SetValue(float val);
//讀取值
bool my_GetValue(int pos,float *val);
//清空值
bool my_ClearValue(void);
#endif
----------------------------------------------
libtest.cpp
--------------------------------------------
#include "libtest.h"
#include
std::vector myList;//存放資訊
//設定值
bool my_SetValue(float val)
{
myList.push_back(val);
return true;
}
//讀取值
bool my_GetValue(int pos,float *val)
{
if(pos < myList.size())
{
*val=myList[pos];
return true;
}
return false;
}
//清空值
bool my_ClearValue(void)
{
myList.clear();
}
------------------------------------
寫值程式write.cpp
-------------------------------------
#include "libtest.h"
int main()
{
float val=1.0;
my_SetValue(val);
float TestRes;
my_GetValue(0,&TestRes); //取剛放入的第一個,這裡有得到TestRes=1.0
}
------------------------------------
寫值程式read.cpp
-------------------------------------
#include "libtest.h"
int main()
{
float TestRes;
my_GetValue(0,&TestRes); //取剛放入的第一個,得不到值,my_GetValue傳回false,即動态庫中myList.size()=0
}
問下這種想法是否可行,來實作從一個程式寫值到so的變量,再讓另一個程式讀出來??
如果可行,我這裡的問題是什麼,動态庫的記憶體發生了什麼變化嗎??
------解決方案--------------------
直接使用共享記憶體就行了,友善,而且不需要so。
------解決方案--------------------
源代碼是從别人的文章中抄過來的,不是原創,不過寫得不錯,主要是描述兩個不同的程序從共享記憶體中存取資料的技術,我加了點分析:
第一個是寫資料:
#include
#include
#include
#include
typedef struct{
char name[4];
int age;
} people;
main(int argc, char** argv)
{
int shm_id,i;
key_t key;
char temp;
people *p_map;
char* name = "/dev/shm/myshm2";
key = ftok(name,0);
if(key==-1)
perror("ftok error");
shm_id=shmget(key,4096,IPC_CREAT);
if(shm_id==-1)
{
perror("shmget error");
return;
}
p_map=(people*)shmat(shm_id,NULL,0);
temp='a';
for(i = 0;i<10;i++)
{
temp+=1;
memcpy((*(p_map+i)).name,&temp,1);
(*(p_map+i)).age=20+i;
}
if(shmdt(p_map)==-1)
perror(" detach error ");
}
#include
#include
#include
#include
typedef struct{
char name[4];
int age;
} people;
main(int argc, char** argv)
{
int shm_id,i;
key_t key;
people *p_map;
char* name = "/dev/shm/myshm2";
key = ftok(name,0);
if(key == -1)
perror("ftok error");
shm_id = shmget(key,4096,IPC_CREAT);
if(shm_id == -1)
文章評論