python 讀取共享內存


測試環境 centos7 python3.6.5

首先使用c創建內存,這里的方法是:作為參數讀一個二進制數據文件進去,把文件的內容作為共享內存的內容

 定義塊

#include <stdio.h>
#include <sys/shm.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int        id = 0;
    char    *data = NULL;
    FILE    *fp = NULL;
    int        totle_len = 0;
    int        len = 0;
    char    buf[1024] = {0};
    
    if (argc < 2)
    {
        printf("args too less\n");
        return 0;
    }
    
    id = shmget(123559, 21 * 1024 * 1024, IPC_CREAT | 0777);
    if (id < 0)
    {
        printf("get id failed\n");
        return 0;
    }
    
    data = shmat(id, NULL, 0);
    if (data == NULL)
    {
        printf("shamt failed\n");
        return 0;
    }
    
    fp = fopen(argv[1], "rb");
    if (fp == NULL)
    {
        printf("open %s failed\n", argv[1]);
        return 0;
    }
    
    while (totle_len <= 12 + 20 * 1024 * 1024)
    {
        len = fread(buf, 1, 1024, fp);
        if (len <= 0)
        {
            break;
        }
        memcpy(data + totle_len, buf, len);
        totle_len += len;
    }

fclose(fp);    
    return 0;
}

 

使用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)

 塊的大小和塊號可以設置,注意讀取的時候 二進制文件的數據格式要保持一致否則讀不出來正確的東西


免責聲明!

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



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