DBus 入門與應用 -- DBus 的 C 編程接口



轉載請注明出處。               作者: 唐風  


最近在學 Dbus,不過總是不得其門而入。

大部分資料都講了很多東西卻最終沒有讓我搞清楚怎么用 DBus,不就是一個 IPC 通信的工具么?就沒有一點實用些的資料么?看了很多資料之后還是覺得只見樹木不見森林。仔細整理下思路,覺得還是應該從最基本的方面入門,先從 DBus 的 C API 入手學習,有了這些知識,就算麻煩,也可以先在完成一個基本功能的例子程序的同時大概的知道 DBus 的運行機制。

在網上找到這么一篇文章:http://www.matthew.ath.cx/misc/dbus, 正合我意,下面的內容基本是對這篇文章的翻譯和擴充。

注意:

  1. 翻譯沒有得到原文作者同意,原文也很簡單易懂,最好去讀原文。如果收到投訴,我會立即撤掉本文的。
  2. 本文不是一篇好的 DBus 入門,有很多基本的東西不在記述之內。
  3. 一般情況下不會直接使用 C API 進行 DBus 的編程,而是使用某種 DBus-binding,但我覺得理解 DBus 的 C API 對完整地理解 DBus 是非常重要的。
  4. 雖然 DBus 是用 C 寫的,而且本文寫的是 C API,但是 DBus 設計中充滿的面向對象的思想,請注意。


一、共通部分的代碼

在使用 DBus 進行通信的時候,有一些代碼是無論如何都會使用到的。首先,你必須要連接上 Dbus,一般來說,系統中會有一個 System Bus 和一個 Session Bus(他們的差別,請參考我另外的筆記)。其次,你需要在 Dbus 中注冊一個名字,用於標識自己。為了簡單起見,這里先不考慮重名的情況:

共通用代碼
  1. DBusError err;
  2. DBusConnection* conn;
  3. int ret;
  4. // initialise the errors
  5. dbus_error_init(&err);
  6.  
  7. // connect to the bus
  8. conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
  9. if (dbus_error_is_set(&err)) {
  10.     fprintf(stderr, "Connection Error (%s)\n", err.message);
  11.     dbus_error_free(&err);
  12. }
  13. if (NULL == conn) {
  14.     exit(1);
  15. }
  16. // request a name on the bus
  17. ret = dbus_bus_request_name(conn, "test.method.server",
  18.                             DBUS_NAME_FLAG_REPLACE_EXISTING
  19.                             , &err);
  20. if (dbus_error_is_set(&err)) {
  21.     fprintf(stderr, "Name Error (%s)\n", err.message);
  22.     dbus_error_free(&err);
  23. }
  24. if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
  25.     exit(1);
  26. }

一般來說,連接上 Dbus 和注冊一個名稱,應該是在程序最開始運行的時候就會進行的操作。

當然,在程序的結束的時候,需要關閉掉與 Dbus 的連接。使用下面的函數:

Code Snippet
  1. dbus_connection_close(conn);

二、發送信號(Sending Signal)

信號是一種廣播的消息,你可以簡單的發出一個信號,這樣,所有連接在 DBus 總線上並注冊了接受對應信號的進程,都會收到這個信號。為了發出一個信號,需要的只是創建一個 DBusMessage 對象來代表信號,然后追加上一些需要發出的參數,就可以發向總線了。發完之后還需要釋放掉 Message。如果內存不足的話,這下面不少函數都會返回 false,所以一般情況下你都需要處理這些情況的返回值。

發送信號
  1. dbus_uint32_t serial = 0; // unique number to associate replies with requests
  2. DBusMessage* msg;
  3. DBusMessageIter args;
  4.  
  5. // create a signal and check for errors
  6. msg = dbus_message_new_signal("/test/signal/Object", // object name of the signal
  7.                               "test.signal.Type", // interface name of the signal
  8.                               "Test"); // name of the signal
  9. if (NULL == msg)
  10. {
  11.     fprintf(stderr, "Message Null\n");
  12.     exit(1);
  13. }
  14.  
  15. // append arguments onto signal
  16. dbus_message_iter_init_append(msg, &args);
  17. if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
  18.     fprintf(stderr, "Out Of Memory!\n");
  19.     exit(1);
  20. }
  21.  
  22. // send the message and flush the connection
  23. if (!dbus_connection_send(conn, msg, &serial)) {
  24.     fprintf(stderr, "Out Of Memory!\n");
  25.     exit(1);
  26. }
  27. dbus_connection_flush(conn);
  28.  
  29. // free the message
  30. dbus_message_unref(msg);

三、調用方法(Calling a Method)

調用一個遠程方法(remote method)與發送一個信號(sending a signal)是很類似的。需要創建一個 DBusMessage,然后通過注冊在 DBus 上的名稱指定發送的對象。然后追加相應的參數,但調用方法分為兩種,一種是阻塞式的,另一種則可以異步調用。異步調用的時候會得到一個 DBusMessage* 的返回,從這個 DBusMessage 中可以獲取一些返回的參數。

調用方法1
  1. DBusMessage* msg;
  2. DBusMessageIter args;
  3. DBusPendingCall* pending;
  4.  
  5. msg = dbus_message_new_method_call("test.method.server", // target for the method call
  6.                                    "/test/method/Object", // object to call on
  7.                                    "test.method.Type", // interface to call on
  8.                                    "Method"); // method name
  9. if (NULL == msg) {
  10.     fprintf(stderr, "Message Null\n");
  11.     exit(1);
  12. }
  13.  
  14. // append arguments
  15. dbus_message_iter_init_append(msg, &args);
  16. if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {
  17.     fprintf(stderr, "Out Of Memory!\n");
  18.     exit(1);
  19. }
  20.  
  21. // send message and get a handle for a reply
  22. if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
  23.     fprintf(stderr, "Out Of Memory!\n");
  24.     exit(1);
  25. }
  26. if (NULL == pending) {
  27.     fprintf(stderr, "Pending Call Null\n");
  28.     exit(1);
  29. }
  30. dbus_connection_flush(conn);
  31.  
  32. // free message
  33. dbus_message_unref(msg);

調用方法2
  1. bool stat;
  2. dbus_uint32_t level;
  3.  
  4. // block until we receive a reply
  5. dbus_pending_call_block(pending);
  6.  
  7. // get the reply message
  8. msg = dbus_pending_call_steal_reply(pending);
  9. if (NULL == msg) {
  10.     fprintf(stderr, "Reply Null\n");
  11.     exit(1);
  12. }
  13. // free the pending message handle
  14. dbus_pending_call_unref(pending);
  15.  
  16. // read the parameters
  17. if (!dbus_message_iter_init(msg, &args))
  18.     fprintf(stderr, "Message has no arguments!\n");
  19. else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args))
  20.     fprintf(stderr, "Argument is not boolean!\n");
  21. else
  22.     dbus_message_iter_get_basic(&args, &stat);
  23.  
  24. if (!dbus_message_iter_next(&args))
  25.     fprintf(stderr, "Message has too few arguments!\n");
  26. else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
  27.     fprintf(stderr, "Argument is not int!\n");
  28. else
  29.     dbus_message_iter_get_basic(&args, &level);
  30.  
  31. printf("Got Reply: %d, %d\n", stat, level);
  32.  
  33. // free reply and close connection
  34. dbus_message_unref(msg);

四、接收消息(Receiving a Signal)

接下來的兩種操作主要是從總線從讀取消息並處理這些消息。

要接收一個消息,你首先需要告訴 DBus 你對什么樣的消息感興趣:

接收消息1
  1. // add a rule for which messages we want to see
  2. dbus_bus_add_match(conn,
  3.                    "type='signal',interface='test.signal.Type'",
  4.                    &err); // see signals from the given interface
  5. dbus_connection_flush(conn);
  6. if (dbus_error_is_set(&err)) {
  7.     fprintf(stderr, "Match Error (%s)\n", err.message);
  8.     exit(1);
  9. }

然后,進程就可以在一個循環中等待這類消息的發生了:

接收消息2
  1. / loop listening for signals being emmitted
  2. while (true) {
  3.  
  4.     // non blocking read of the next available message
  5.     dbus_connection_read_write(conn, 0);
  6.     msg = dbus_connection_pop_message(conn);
  7.  
  8.     // loop again if we haven't read a message
  9.     if (NULL == msg) {
  10.         sleep(1);
  11.         continue;
  12.     }
  13.  
  14.     // check if the message is a signal from the correct interface and with the correct name
  15.     if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
  16.         // read the parameters
  17.         if (!dbus_message_iter_init(msg, &args))
  18.             fprintf(stderr, "Message has no arguments!\n");
  19.         else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
  20.             fprintf(stderr, "Argument is not string!\n");
  21.         else {
  22.             dbus_message_iter_get_basic(&args, &sigvalue);
  23.             printf("Got Signal with value %s\n", sigvalue);
  24.         }
  25.     }
  26.  
  27.     // free the message
  28.     dbus_message_unref(msg);
  29. }

五、提供被遠程調用的方法(Exposing a Method to be called)

在第二節中,我們看到了調用一個遠程方法,這節就是告訴我們怎么樣提供一個方法讓別的應用程序調用。用下面的程序,就可以把方法關聯在那些提供給外部的方法上,並解析出相應的參數,最后構建一個消息返回給調用方法的應用程序。

提供被遠程調用的方法1
  1. // loop, testing for new messages
  2. while (true) {
  3.     // non blocking read of the next available message
  4.     dbus_connection_read_write(conn, 0);
  5.     msg = dbus_connection_pop_message(conn);
  6.   
  7.     // loop again if we haven't got a message
  8.     if (NULL == msg) {
  9.         sleep(1);
  10.         continue;
  11.     }
  12.  
  13.     // check this is a method call for the right interface and method
  14.     if (dbus_message_is_method_call(msg, "test.method.Type", "Method"))
  15.         reply_to_method_call(msg, conn);
  16.  
  17.     // free the message
  18.     dbus_message_unref(msg);
  19. }

 

提供被遠程調用的方法2
  1. void reply_to_method_call(DBusMessage* msg, DBusConnection* conn)
  2. {
  3.     DBusMessage* reply;
  4.     DBusMessageIter args;
  5.     DBusConnection* conn;
  6.     bool stat = true;
  7.     dbus_uint32_t level = 21614;
  8.     dbus_uint32_t serial = 0;
  9.     char* param = "";
  10.  
  11.     // read the arguments
  12.     if (!dbus_message_iter_init(msg, &args))
  13.         fprintf(stderr, "Message has no arguments!\n");
  14.     else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
  15.         fprintf(stderr, "Argument is not string!\n");
  16.     else
  17.         dbus_message_iter_get_basic(&args, &param);
  18.     printf("Method called with %s\n", param);
  19.  
  20.     // create a reply from the message
  21.     reply = dbus_message_new_method_return(msg);
  22.  
  23.     // add the arguments to the reply
  24.     dbus_message_iter_init_append(reply, &args);
  25.     if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat)) {
  26.         fprintf(stderr, "Out Of Memory!\n");
  27.         exit(1);
  28.     }
  29.     if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) {
  30.         fprintf(stderr, "Out Of Memory!\n");
  31.         exit(1);
  32.     }
  33.  
  34.     // send the reply && flush the connection
  35.     if (!dbus_connection_send(conn, reply, &serial)) {
  36.         fprintf(stderr, "Out Of Memory!\n");
  37.         exit(1);
  38.     }
  39.     dbus_connection_flush(conn);
  40.  
  41.     // free the reply
  42.     dbus_message_unref(reply);
  43. }

 

這就基本上全部了。但用這些來理解 DBus 顯然還遠遠不夠。接下來,就要對這些程序以及背后的理念進行具體的探究了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM