gpt4 book ai didi

python - 使用 DBus 守护进程将消息从 C 应用程序交换到 python 应用程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:56 26 4
gpt4 key购买 nike

您好,我是 DBus 守护进程的新手,我想在 C 应用程序和 python 应用程序之间完成简单的消息交换,它们在自定义的类 linux 环境中运行。我的理解是

  1. 首先,从 init 文件启动 dbus-daemon
  2. 将C应用和python应用注册到D-BUS
  3. 发送消息(这只是一个简单的字符串)在这两个应用程序之间的总线上。

我的问题是关于上面的 (2) 和 (3)。 C应用程序和python应用程序如何注册到同一总线?

此外,需要调用哪些 API 才能在这两个应用程序之间发送字符串消息?

最佳答案

[您要求简单的消息传递]

你真的需要DBus吗?

如果您要求在 C 应用程序和 Python 之间传递简单的消息,为什么不使用像 Rabbit/ZeroMQ 这样的消息传递库?这些已经解决了与传递/接收消息相关的所有问题。

而且,如果您想将依赖性保持在最低限度,您可以使用 UNIX 套接字或什至一些简单的 TCP/UDP 数据报。

编辑:因为我试图说服您研究 ZeroMQ 作为您的 IPC 平台以及它是多么简单,这里有一个示例 C“客户端”向服务器发送完整的数据报,服务器回复。

ZeroMQ Client Example in C:

// Hello World client
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main ( void )
{
printf ( "Connecting to hello world server…\n" );
void *context = zmq_ctx_new ();
void *requester = zmq_socket ( context, ZMQ_REQ );
zmq_connect ( requester, "tcp://localhost:5555" );

int request_nbr;
for ( request_nbr = 0; request_nbr != 10; request_nbr++ ) {
char buffer [10];
printf ( "Sending Hello %d…\n", request_nbr );
zmq_send ( requester, "Hello", 5, 0 );
zmq_recv ( requester, buffer, 10, 0 );
printf ( "Received World %d\n", request_nbr );
}
zmq_close (requester);
zmq_ctx_destroy (context);
return 0;
}

服务器也同样简单:

ZeroMQ Server Example in C

// Hello World server

#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

int main ( void )
{
// Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket ( context, ZMQ_REP );
int rc = zmq_bind ( responder, "tcp://*:5555" );
assert ( rc == 0 );

while ( 1 ) {
char buffer [10];
zmq_recv ( responder, buffer, 10, 0 );
printf ( "Received Hello\n" );
sleep ( 1 ); // Do some 'work'
zmq_send ( responder, "World", 5, 0 );
}
return 0;
}

关于python - 使用 DBus 守护进程将消息从 C 应用程序交换到 python 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577527/

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