gpt4 book ai didi

c - 在串行链路上等待读取数据的通知

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:08 27 4
gpt4 key购买 nike

我尝试向我的 g_main_loop 添加一个新源,它是外围串行线路上的文件描述符。

我试试这段代码:

GError* error;
GIOChannel* channel;
channel=g_io_channel_unix_new(fd_serial_line_dev);
g_io_add_watch(channel, G_IO_IN, cb_1, NULL);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, &error);
g_io_channel_set_buffered(channel, FALSE);

回调是:

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data)
{
gchar** line=NULL;
GIOStatus status;
GError* error;

printf("cb\n");

status=g_io_channel_read_line(source, line, NULL, NULL, &error);

if(G_IO_STATUS_NORMAL == status)
{
printf("callback : data : %s\n", *line);
g_free(*line);
//g_io_channel_seek_position(source, 0, G_SEEK_CUR, NULL);
}

return TRUE;
}

当我在串行线上发送数据时,我获得了一个每次调用 cb_1 的无限循环。

我看不出我的错误在哪里,我预计串行线的文件描述符内的读取将足以在下一个 g 主循环迭代期间停止对回调的调用......

最佳答案

尝试在 g_io_add_watch 之后立即添加 g_io_channel_unref(channel)。然后在你的回调中添加

if(G_IO_STATUS_EOF == status)
return FALSE;

g_io_channel_*_new() returns a GIOChannel object with a reference count of one. g_io_add_watch() adds a further reference count - if you decrement it by 1, the callback will be disconnected and the relevant GSource object removed when the callback returns FALSE, which it should do when it detects end-of-file, or if you call g_source_remove() on the return value of g_io_add_watch()

关于c - 在串行链路上等待读取数据的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com