Skip to content

Instantly share code, notes, and snippets.

@sumantro93
Last active August 14, 2023 12:31
Show Gist options
  • Save sumantro93/861dc2f235dae0605fb8d5987f7563ae to your computer and use it in GitHub Desktop.
Save sumantro93/861dc2f235dae0605fb8d5987f7563ae to your computer and use it in GitHub Desktop.
dbus_example.c
#include <stdio.h>
#include <dbus/dbus.h>
#include <stdlib.h>
#include <unistd.h>
void send_signal(DBusConnection *conn) {
DBusMessage* msg;
DBusMessageIter args;
msg = dbus_message_new_signal("/test/signal/Object", "test.signal.Type", "Test");
if (NULL == msg) {
fprintf(stderr, "Message Null\n");
exit(1);
}
dbus_message_iter_init_append(msg, &args);
char* sigvalue = "Hello from our test application!";
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
if (!dbus_connection_send(conn, msg, NULL)) {
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
dbus_connection_flush(conn);
printf("Signal Sent!\n");
dbus_message_unref(msg);
}
void receive_signal(DBusConnection *conn) {
DBusMessage* msg;
dbus_bus_add_match(conn, "type='signal',interface='test.signal.Type'", NULL);
dbus_connection_flush(conn);
while (1) {
dbus_connection_read_write(conn, 0);
msg = dbus_connection_pop_message(conn);
if (NULL == msg) {
usleep(10000);
continue;
}
if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
printf("Received Test signal with message: %s\n", dbus_message_get_member(msg));
}
dbus_message_unref(msg);
}
}
int main(int argc, char** argv) {
DBusConnection* conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (dbus_error_is_set(&err)) {
fprintf(stderr, "Connection Error: %s\n", err.message);
dbus_error_free(&err);
return 1;
}
if (NULL == conn) {
fprintf(stderr, "Connection Null\n");
return 1;
}
send_signal(conn);
receive_signal(conn);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment