2014-01-09 121 views
1

我需要你的帮助。GMainLoop和TCP监听线程

我有附带超时回调主回路GMainLoop:

MainLoop = g_main_loop_new(NULL, FALSE); 
g_timeout_add_seconds(Interval, TimeoutCallback, (gpointer) Rec); 
g_main_loop_run(MainLoop); 

而且监听套接字:

int ControlServer::GStart() 
{ 
    int listenfd; 
    GIOChannel *in; 
    socklen_t addr_len; 
    listenfd = TcpListen(host, port, &addr_len); 
    in = g_io_channel_unix_new(listenfd); 
    g_io_add_watch(in, G_IO_IN, (GIOFunc) Handler, (gpointer) Rec); 
    g_io_channel_unref(in); 
    return 0; 
} 

所有的好和超时功能正常工作,直到任何客户端没有连接听取插座。连接后,超时不能在客户端连接的所有时间工作。我认为它与线程相关,就像GLib文档默认的GMainContext在一个线程中执行的所有动作一样。我修改这个代码:

int ControlServer::GThStart() 
{ 
    int listenfd; 
    socklen_t addr_len; 
    GIOChannel *Channel; 
    GSource *Source; 
    GMainContext *Context; 

    listenfd = TcpListen(host, port, &addr_len); 
    Channel = g_io_channel_unix_new(listenfd); 
    Source = g_io_create_watch(Channel, G_IO_IN); 
    g_source_set_callback(Source, (GSourceFunc) Handler, (gpointer) Rec, NULL); 
    Context = g_main_context_new(); 
    g_source_attach(Source, Context); 
    g_source_unref(Source); 
    return 0; 
} 

但现在插座着,却没有任何客户端可以连接到它和处理函数不会被调用。

处理程序代码如下:

bool ControlServer::Handler(GIOChannel *in, GIOCondition condition, gpointer data) 
{ 
    Recorder *Rec = (Recorder *) data; 
    struct sockaddr_storage income; 
    int insock, newsock; 
    socklen_t income_len; 
    struct sockaddr peer; 
    socklen_t size; 
    Access *access; 

    insock = g_io_channel_unix_get_fd(in); 
    income_len = sizeof(income); 
    newsock = accept(insock, (struct sockaddr *) &income, &income_len); 
    size = sizeof(peer); 
    getpeername(newsock, &peer, &size); 
    struct sockaddr_in *ipv4 = (struct sockaddr_in *) &peer; 
    access = new Access(newsock, ipv4, MAXN); 

    access->Cycle(Rec); 

    delete access; 
    return true; 
} 

类“访问”检查客户的权利和实现无限循环的执行协议处理交换,同时客户端或服务器没有密切的联系。

do 
    { 
     result = DoCycle(Rec); 
     sprintf(str, "DEBUG: DoCycle(Rec) returns '%d'\n", result); 
     AppendLog(str, class_name, DEBUG); 
    } while (result != -1); 

只有当连接关闭或通过TCP错误交换数据时,DoCycle()才返回'-1'。

有什么不对? 谢谢!

+0

是什么处理程序是什么样子? – nemequ

+0

我刚刚添加Handler的代码和一些解释。 – Xuch

回答

1

问题是功能int ControlServer::GThStart(),你应该添加GSourceGMainContextGMainLoop的,而不是新的上下文及尝试:

g_source_attach(Source,g_main_loop_get_context(MainLoop));