Linux c共享内存发送和接收 python端接收 示例代码
发送端:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <signal.h>
#define IPC_KEY 74565
int shmid = 0;
void sigHandle(int sig)
{
if(sig == SIGINT) {
shmctl(shmid, IPC_RMID, NULL);
exit(0);
}
}
int main()
{
signal(SIGINT, sigHandle);
shmid = shmget(IPC_KEY,32, IPC_CREAT | 0664);
if(shmid < 0)
{
perror("shmget error\n");
return -1;
}
char *shm_start = (char*)shmat(shmid,NULL,0);
if(shm_start == (void*)-1)
{
perror("shmat error");
return -1;
}
int i = 1;
while(1)
{
sprintf(shm_start,"%d\n",i++);
sleep(1);
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
c接收端:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/shm.h>
#define IPC_KEY 74565
int main()
{
int shmid = -1;
shmid = shmget(IPC_KEY,32, IPC_CREAT|0664);
if(shmid < 0)
{
perror("shmget error\n");
return -1;
}
char *shm_start = (char*)shmat(shmid,NULL,0);
if(shm_start == (void*)-1)
{
perror("shmat error");
return -1;
}
while(1)
{
printf("不断的问自己:%s",shm_start);
sleep(1);
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
python 接收端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script dumps the content of a shared memory block
# used by Linux/Cdorked.A into a file named httpd_cdorked_config.bin
# when the machine is infected.
#
# Some of the data is encrypted. If your server is infected and you
# would like to help, please send the httpd_cdorked_config.bin
# to our lab for analysis. Thanks!
#
# Marc-Etienne M.Léveillé <leve...@eset.com>
#
from ctypes import *
import time
import json
SHM_SIZE = 32
SHM_KEY = 74565
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:
addr = shmat(shmid, None, 0)
while(1):
print(string_at(addr,SHM_SIZE))
#传输为json数据时,解析方法:
strstr = string_at(addr, SHM_SIZE).strip(b"\x00".decode())
print(strstr, type(strstr))
json_s = json.loads(strstr)
print(json_s, type(json_s))
ret1 = json_s["sensor1"]
print(ret1)
ret2 = json_s["sensor2"]
print(ret2)
time.sleep(1)