我正在为我的状态栏编写一个插件来打印 MPD 状态,目前使用的是libmpdclient库。如果 MPD 重新启动,它必须能够正确处理丢失的连接,但是mpd_connection_get_error
对现有mpd_connection对象的简单检查不起作用——它只能在初始mpd_connection_new
失败时检测到错误。
这是我正在使用的简化代码:
#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);
}
}
当 MPD 在上述程序执行期间停止时,它会出现以下段错误:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007fb2fd9557e0 in mpd_status_get_state () from /usr/lib/libmpdclient.so.2
我能想到的使程序安全的唯一方法是在每次迭代中建立一个新的连接,这是我希望避免的。但是,如果各个libmpdclient
函数调用之间的连接丢失了怎么办?我应该多久检查一次,更重要的是如何检查连接是否仍然存在?