gpt4 book ai didi

python - 如何处理 C 和 Python 之间的 IPC?

转载 作者:太空狗 更新时间:2023-10-30 01:29:36 31 4
gpt4 key购买 nike

我有一个包含两个进程的应用程序,一个使用 C 语言,一个使用 Python。 C 进程完成所有繁重的工作,而 Python 进程处理用户界面。

C 程序每秒写入 4 次大型缓冲区,Python 进程读取此数据。至此,与 Python 进程的通信已由 AMQP 完成。我更愿意在两个进程之间设置一些内存共享以减少开销并提高性能。

我在这里有哪些选择?理想情况下,我会让 Python 进程直接读取物理内存(最好从内存而不是磁盘),然后使用信号量或类似的东西处理竞争条件。然而,这是我几乎没有经验的事情,所以如果能得到任何帮助,我将不胜感激。

顺便说一句,我正在使用 Linux。

最佳答案

这个问题已经问了很久了。我相信提问者已经有了答案,所以我写了这个答案给后来的人。

/*C code*/

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

#define GETEKYDIR ("/tmp")
#define PROJECTID (2333)
#define SHMSIZE (1024)

void err_exit(char *buf) {
fprintf(stderr, "%s\n", buf);
exit(1);
}


int
main(int argc, char **argv)
{

key_t key = ftok(GETEKYDIR, PROJECTID);
if ( key < 0 )
err_exit("ftok error");

int shmid;
shmid = shmget(key, SHMSIZE, IPC_CREAT | IPC_EXCL | 0664);
if ( shmid == -1 ) {
if ( errno == EEXIST ) {
printf("shared memeory already exist\n");
shmid = shmget(key ,0, 0);
printf("reference shmid = %d\n", shmid);
} else {
perror("errno");
err_exit("shmget error");
}
}

char *addr;

/* Do not to specific the address to attach
* and attach for read & write*/
if ( (addr = shmat(shmid, 0, 0) ) == (void*)-1) {
if (shmctl(shmid, IPC_RMID, NULL) == -1)
err_exit("shmctl error");
else {
printf("Attach shared memory failed\n");
printf("remove shared memory identifier successful\n");
}

err_exit("shmat error");
}

strcpy( addr, "Shared memory test\n" );

printf("Enter to exit");
getchar();

if ( shmdt(addr) < 0)
err_exit("shmdt error");

if (shmctl(shmid, IPC_RMID, NULL) == -1)
err_exit("shmctl error");
else {
printf("Finally\n");
printf("remove shared memory identifier successful\n");
}

return 0;
}
#python 

# Install sysv_ipc module firstly if you don't have this
import sysv_ipc as ipc

def main():
path = "/tmp"
key = ipc.ftok(path, 2333)
shm = ipc.SharedMemory(key, 0, 0)

#I found if we do not attach ourselves
#it will attach as ReadOnly.
shm.attach(0,0)
buf = shm.read(19)
print(buf)
shm.detach()
pass

if __name__ == '__main__':
main()

C 程序需要先执行,不要在 python 代码执行之前就停止它,它会创建共享内存段并向其中写入一些东西。然后 Python 代码附加相同的段并从中读取数据。

完成所有事情后,按回车键停止C程序并删除共享内存ID。

我们可以在这里看到更多关于 SharedMemory for python 的信息: http://semanchuk.com/philip/sysv_ipc/#shared_memory

关于python - 如何处理 C 和 Python 之间的 IPC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120373/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com