最近我使用dbus作为IPC,但我遇到了一些问题:
如何处理发送消息失败:dbus_connection_send
可以发送dbus消息,但文档说:
因为这只会使消息排队,所以它失败的唯一原因是 缺乏记忆力。即使断开连接,也不会出现错误 被退回如果函数由于内存不足而失败,则返回 假。该功能永远不会因其他原因而失败;即使是 虽然连接已断开连接,但您可以对传出消息进行排队 显然它不会被发送。
所以当连接断开时如何处理这种情况以确保传出队列中的所有消息都成功发送
如何通过dbus_connection_dispatch
接收消息时处理连接断开连接,我的代码是这样的,但我认为重新连接到dbus时会丢失一些消息
void DbusMessageWrapper::messageDispatchThreadFunction() { start: struct pollfd *pollFd = &m_pollFd; if (!dbus_connection_set_watch_functions(m_dbusConnection, addWatch, removeWatch, NULL, this, NULL)) { TONLY_ERROR("dbus_connection_set_watch_functions failed"); return; }
if (!dbus_connection_add_filter(m_dbusConnection, messageProcessFunction, this, NULL)) { TONLY_INFO("dbus_connection_add_filter failed"); return; } int iret = 0; for (; !m_isShuttingDown;) { iret = poll(pollFd, 1, -1); if (iret < 0) { ///If poll return -1, we think that poll does not work on current plateform, so emit a ALERT log and exit application TONLY_ALERT("poll for dbus fd failed, the application will exit."); exit(1); } /** * If poll return POLLHUP/POLLRDHUP/POLLERR event, we think the dbus connection have disconnected from dbus deamon * we should release the request name and close current dbus connection, then reconnect to the dbus deamon, * aslo add the message observer watch to dbus connection again */ if ((pollFd->revents & POLLHUP) || (pollFd->revents & POLLRDHUP) || (pollFd->revents & POLLERR)) { TONLY_ERROR("poll error event occured, will reconnect to dbus deamon."); dbusDisConnect(); dbusConnect(); ///reinstall the message observer auto observers = m_observers; m_observers.clear(); for (auto it = observers.begin(); it != observers.end(); it++) { addMessageObserver({it->second}); } goto start; } unsigned int flags = 0; if (pollFd->revents & POLLIN) { flags |= DBUS_WATCH_READABLE; } ///wait for there are enougth memory while (!dbus_watch_handle(m_watch, flags)) { TONLY_ERROR("Dbus need more memory"); sleep(1); } while (dbus_connection_get_dispatch_status(m_dbusConnection) == DBUS_DISPATCH_DATA_REMAINS) { dbus_connection_dispatch(m_dbusConnection); } }
}