#include <stdlib.h>
#include <dbus/dbus.h>
int main(int argc, char **argv) {
DBusConnection *conn;
DBusError err;
// 初始化错误结构体
dbus_error_init(&err);
// 连接到系统DBus总线
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err)) {
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
return EXIT_FAILURE;
}
if (conn == NULL) {
fprintf(stderr, "Connection Null\n");
return EXIT_FAILURE;
}
// 创建DBus消息
DBusMessage *msg;
msg = dbus_message_new_method_call("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListNames");
// 发送DBus消息并等待回复
DBusMessage *reply;
reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
if (dbus_error_is_set(&err)) {
fprintf(stderr, "Reply Error (%s)\n", err.message);
dbus_error_free(&err);
return EXIT_FAILURE;
}
if (reply == NULL) {
fprintf(stderr, "Reply Null\n");
return EXIT_FAILURE;
}
// 从DBus回复中获取数据
char *str;
if (!dbus_message_get_args(reply, &err, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &str, DBUS_TYPE_INVALID)) {
fprintf(stderr, "Get Args Error (%s)\n", err.message);
dbus_error_free(&err);
return EXIT_FAILURE;
}
printf("List of Services:\n%s\n", str);
// 释放资源
dbus_message_unref(msg);
dbus_message_unref(reply);
dbus_connection_unref(conn);
return EXIT_SUCCESS;
}
评论