1.server.c
#include <stdio.h>
#include <string.h>
#include <dbus/dbus.h>
int main()
{
DBusConnection *connection = NULL;
DBusError error;
dbus_error_init(&error);
connection = dbus_bus_get(DBUS_BUS_SESSION, &error);
if(dbus_error_is_set(&error))
{
printf("连接DBUS失败: %s\n", error.message);
dbus_error_free(&error);
return 1;
}
printf("等待客户端请求...\n");
int ret = dbus_bus_request_name(connection, "com.example.TestServer", DBUS_NAME_FLAG_REPLACE_EXISTING, &error);
if(dbus_error_is_set(&error))
{
printf("注册DBUS服务失败: %s\n", error.message);
dbus_error_free(&error);
return 1;
}
while(1)
{
dbus_connection_read_write_dispatch(connection, -1);
DBusMessage *message = NULL;
message = dbus_connection_pop_message(connection);
if(message == NULL)
{
sleep(1);
continue;
}
if(dbus_message_is_method_call(message, "com.example.TestInterface", "Hello"))
{
DBusMessage *reply;
const char *reply_str = "Hello, Client!";
reply = dbus_message_new_method_return(message);
dbus_message_append_args(reply, DBUS_TYPE_STRING, &reply_str, DBUS_TYPE_INVALID);
dbus_connection_send(connection, reply, NULL);
dbus_message_unref(reply);
}
dbus_message_unref(message);
}
return 0;
}
2,client.c
#include <stdio.h>
#include <string.h>
#include <dbus/dbus.h>
int main()
{
DBusConnection *connection = NULL;
DBusError error;
dbus_error_init(&error);
connection = dbus_bus_get(DBUS_BUS_SESSION, &error);
if(dbus_error_is_set(&error))
{
printf("连接DBUS失败: %s\n", error.message);
dbus_error_free(&error);
return 1;
}
const char *server_name = "com.example.TestServer";
DBusMessage *message = NULL;
message = dbus_message_new_method_call(server_name, "/com/example/TestObject", "com.example.TestInterface", "Hello");
DBusPendingCall *pending;
dbus_connection_send_with_reply(connection, message, &pending, -1);
//dbus_pending_call_set_timeout(pending, 1000);
dbus_pending_call_block(pending);
DBusMessage *reply;
if(dbus_pending_call_get_completed(pending))
{
reply = dbus_pending_call_steal_reply(pending);
char *str_result;
dbus_message_get_args(reply, NULL, DBUS_TYPE_STRING, &str_result, DBUS_TYPE_INVALID);
printf("接收到来自Server的回复:%s\n", str_result);
dbus_message_unref(reply);
}
dbus_pending_call_unref(pending);
dbus_message_unref(message);
return 0;
}
3.编译源码
$ gcc -g -o server server.c -I/usr/include/dbus-1.0 -I/usr/lib64/dbus-1.0/include -ldbus-1
$ gcc -g -o client client.c -I/usr/include/dbus-1.0 -I/usr/lib64/dbus-1.0/include -ldbus-1
4.运行及其结果
$ ./server
$ ./client
接收到来自Server的回复:Hello, Client!