测试环境 centos7 python3.6.5
首先使用c创建内存,这里的方法是:作为参数读一个二进制数据文件进去,把文件的内容作为共享内存的内容
定义块
#include <stdio.h>
#include <sys/shm.h>
#include <string.h> int main(int argc, char *argv[])
{
int id = ;
char *data = NULL;
FILE *fp = NULL;
int totle_len = ;
int len = ;
char buf[] = {}; if (argc < )
{
printf("args too less\n");
return ;
} id = shmget(, * * , IPC_CREAT | );
if (id < )
{
printf("get id failed\n");
return ;
} data = shmat(id, NULL, );
if (data == NULL)
{
printf("shamt failed\n");
return ;
} fp = fopen(argv[], "rb");
if (fp == NULL)
{
printf("open %s failed\n", argv[]);
return ;
} while (totle_len <= + * * )
{
len = fread(buf, , , fp);
if (len <= )
{
break;
}
memcpy(data + totle_len, buf, len);
totle_len += len;
} fclose(fp);
return ;
}
使用python读取:
from ctypes import *
import numpy as npimport codecs
import datetime SHM_SIZE = 1024*1024*20
SHM_KEY = 123559
OUTFILE="httpd_cdorked_config.bin"
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p shmid = shmget(SHM_KEY, SHM_SIZE, 0o666)
if shmid < 0:
print ("System not infected")
else:
begin_time=datetime.datetime.now()
addr = shmat(shmid, None, 0)
f=open(OUTFILE, 'wb')
rate=int.from_bytes(string_at(addr,4), byteorder='little', signed=True) #这里数据文件是小端int16类型
len_a=int.from_bytes(string_at(addr+4,4), byteorder='little', signed=True)
len_b=int.from_bytes(string_at(addr+8,4), byteorder='little', signed=True)
print(rate,len_a,len_b)
f.write(string_at(addr+12,SHM_SIZE))
f.close()
#print ("Dumped %d bytes in %s" % (SHM_SIZE, OUTFILE))
print("Success!",datetime.datetime.now()-begin_time)
块的大小和块号可以设置,注意读取的时候 二进制文件的数据格式要保持一致否则读不出来正确的东西