libmpdclient:检测与MPD守护程序的丢失连接

时间:2015-01-06 21:20:59

标签: c mpd

我正在为我的状态栏编写一个插件来打印MPD状态,目前正在使用libmpdclient库。在重新启动MPD的情况下,必须能够正确处理丢失的连接,但在现有mpd_connection对象上使用mpd_connection_get_error进行简单检查不起作用 - 它只能在初始{{1}时检测到错误失败。

这是我正在使用的简化代码:

mpd_connection_new

当MPD在执行上述程序期间停止时,它会以以下步骤进行分段:

#include <stdio.h>
#include <unistd.h>
#include <mpd/client.h>

int main(void) {
    struct mpd_connection* m_connection = NULL;
    struct mpd_status* m_status = NULL;
    char* m_state_str;

    m_connection = mpd_connection_new(NULL, 0, 30000);

    while (1) {
        // this check works only on start up (i.e. when mpd_connection_new failed),
        // not when the connection is lost later
        if (mpd_connection_get_error(m_connection) != MPD_ERROR_SUCCESS) {
            fprintf(stderr, "Could not connect to MPD: %s\n", mpd_connection_get_error_message(m_connection));
            mpd_connection_free(m_connection);
            m_connection = NULL;
        }

        m_status = mpd_run_status(m_connection);
        if (mpd_status_get_state(m_status) == MPD_STATE_PLAY) {
            m_state_str = "playing";
        } else if (mpd_status_get_state(m_status) == MPD_STATE_STOP) {
            m_state_str = "stopped";
        } else if (mpd_status_get_state(m_status) == MPD_STATE_PAUSE) {
            m_state_str = "paused";
        } else {
            m_state_str = "unknown";
        }
        printf("MPD state: %s\n", m_state_str);
        sleep(1);
    }
}

我能想到使程序安全的唯一方法是在每次迭代中建立一个新连接,这是我希望避免的。但是,如果在Program terminated with signal SIGSEGV, Segmentation fault. #0 0x00007fb2fd9557e0 in mpd_status_get_state () from /usr/lib/libmpdclient.so.2 个函数的单个调用之间连接丢失怎么办?多久一次,更重要的是究竟如何,我应该检查连接是否仍然存在?

1 个答案:

答案 0 :(得分:0)

假设“ conn”是使用“ mpd_connection_new”创建的连接:

if (mpd_connection_get_error(conn) == MPD_ERROR_CLOSED) {
    // mpd_connection_get_error_message(conn)
    // will return "Connection closed by the server"
}

您几乎可以在所有libmpdclient调用之后运行此检查,包括“ mpd_recv_idle”或(根据您的示例)“ mpd_run_status”。

我正在使用libmpdclient 2.18,这肯定对我有用。