5_08_GLib库入门与实践_IO通道

简介

GIOChannel数据类型旨在提供一种可移植的方法来使用文件描述符、管道和套接字,并将它们集成到主事件循环中。目前,UNIX平台已完全支持,Windows平台只是部分支持。
要在UNIX系统上创建新的GIOChannel,可以使用使用 g_io_channel_unix_new(),这适用于普通文件描述符、管道和套接字。使用g_io_channel_new_file()可以以独立于系统的方式为文件创建通道。
一旦创建了 GIOChannel,就可以通过函数g_io_channel_read_chars()、g_io_channel_write_chars()、g_io_channel_seek_position()和g_io_channel_shutdown()以通用方式使用它。
GIOChannel的一个重要应用是将其添加到主循环中,接口为g_io_add_watch()或g_io_add_watch_full()。g_io_create_watch指定GIOChannel上感兴趣的事件,g_source_set_callback提供在这些事件发生时的回调函数。
GIOChannel实例的初始引用计数为 1。g_io_channel_ref()和g_io_channel_unref()可用于分别增加或减少引用计数。当引用计数下降到0时,GIOChannel被释放。(但是它不会自动关闭,除非它是使用 g_io_channel_new_file() 创建的。)使用g_io_add_watch()或g_io_add_watch_full()会增加通道的引用计数。
新函数g_io_channel_read_chars()、g_io_channel_read_line()、g_io_channel_read_line_string()、g_io_channel_read_to_end()、g_io_channel_write_chars()、g_io_channel_seek_position()和g_io_channel_flush()不应与已废弃的函数g_io_channel_read()、g_io_channel_write() 和 g_io_channel_seek混合使用,一般来说,尽量不使用已废弃函数。

数据结构

GIOChannel对象的数据结构是一个不透明结构体。

typedef struct _GIOChannel	GIOChannel;

IO通道的状态,枚举类型。

enum GIOStatus;

IO通道返回错误值,枚举类型。

``enum GIOChannelError;``

函数列表

GIOChannel * 	g_io_channel_unix_new ()
gint 	g_io_channel_unix_get_fd ()
GIOChannel * 	g_io_channel_win32_new_fd ()
GIOChannel * 	g_io_channel_win32_new_socket ()
GIOChannel * 	g_io_channel_win32_new_messages ()
void 	g_io_channel_init ()
GIOChannel * 	g_io_channel_new_file ()
GIOStatus 	g_io_channel_read_chars ()
GIOStatus 	g_io_channel_read_unichar ()
GIOStatus 	g_io_channel_read_line ()
GIOStatus 	g_io_channel_read_line_string ()
GIOStatus 	g_io_channel_read_to_end ()
GIOStatus 	g_io_channel_write_chars ()
GIOStatus 	g_io_channel_write_unichar ()
GIOStatus 	g_io_channel_flush ()
GIOStatus 	g_io_channel_seek_position ()
GIOStatus 	g_io_channel_shutdown ()
GIOChannelError 	g_io_channel_error_from_errno ()
GIOChannel * 	g_io_channel_ref ()
void 	g_io_channel_unref ()
GSource * 	g_io_create_watch ()
guint 	g_io_add_watch ()
guint 	g_io_add_watch_full ()
gboolean 	(*GIOFunc) ()
gsize 	g_io_channel_get_buffer_size ()
void 	g_io_channel_set_buffer_size ()
GIOCondition 	g_io_channel_get_buffer_condition ()
GIOFlags 	g_io_channel_get_flags ()
GIOStatus 	g_io_channel_set_flags ()
const gchar * 	g_io_channel_get_line_term ()
void 	g_io_channel_set_line_term ()
gboolean 	g_io_channel_get_buffered ()
void 	g_io_channel_set_buffered ()
const gchar * 	g_io_channel_get_encoding ()
GIOStatus 	g_io_channel_set_encoding ()
gboolean 	g_io_channel_get_close_on_unref ()
void 	g_io_channel_set_close_on_unref ()
GIOError 	g_io_channel_read ()
GIOError 	g_io_channel_write ()
GIOError 	g_io_channel_seek ()
void 	g_io_channel_close ()

函数功能分类

创建

GIOChannel * 	g_io_channel_unix_new ()
GIOChannel * 	g_io_channel_win32_new_fd ()
GIOChannel * 	g_io_channel_win32_new_socket ()
GIOChannel * 	g_io_channel_win32_new_messages ()
GIOChannel * 	g_io_channel_new_file ()

GIOStatus 	g_io_channel_read_chars ()
GIOStatus 	g_io_channel_read_unichar ()
GIOStatus 	g_io_channel_read_line ()
GIOStatus 	g_io_channel_read_line_string ()
GIOStatus 	g_io_channel_read_to_end ()

GIOStatus 	g_io_channel_write_chars ()
GIOStatus 	g_io_channel_write_unichar ()

清空

GIOStatus 	g_io_channel_flush ()

关闭

GIOStatus 	g_io_channel_shutdown ()

参数设置及获取

gsize 	g_io_channel_get_buffer_size ()
void 	g_io_channel_set_buffer_size ()
GIOFlags 	g_io_channel_get_flags ()
GIOStatus 	g_io_channel_set_flags ()
gboolean 	g_io_channel_get_buffered ()
void 	g_io_channel_set_buffered ()
const gchar * 	g_io_channel_get_encoding ()
GIOStatus 	g_io_channel_set_encoding ()
gboolean 	g_io_channel_get_close_on_unref ()
void 	g_io_channel_set_close_on_unref ()
const gchar * 	g_io_channel_get_line_term ()
void 	g_io_channel_set_line_term ()

引用和解引用

GIOChannel * 	g_io_channel_ref ()
void 	g_io_channel_unref ()

其他

gint 	g_io_channel_unix_get_fd ()
void 	g_io_channel_init ()
GIOStatus 	g_io_channel_seek_position ()
GIOChannelError 	g_io_channel_error_from_errno ()
GSource * 	g_io_create_watch ()
guint 	g_io_add_watch ()
guint 	g_io_add_watch_full ()
gboolean 	(*GIOFunc) ()
GIOCondition 	g_io_channel_get_buffer_condition ()

函数功能说明及综合演示

使用IO通道接口读取文件

示例代码如下:
源码见glib_examples\glib_iochannel\glib_iochannel_file

#include <unistd.h>
#include <fcntl.h>
#include <glib.h>

gint main(gint argc, gchar **argv)
{
    int fd = 0;
    GIOChannel *channel = NULL;
    GIOStatus st = G_IO_STATUS_ERROR;
    gchar *str_return;
    gsize length, terminator_pos;
    GError *error = NULL;

    fd = open("/etc/os-release", O_RDONLY);

    channel = g_io_channel_unix_new (fd);

    while(1) {
        st = g_io_channel_read_line (channel, &str_return, &length, &terminator_pos,&error);
        if(G_IO_STATUS_NORMAL == st) {
            g_print("read_line: %s \n", str_return);
        } else {
            g_print("read error: %d! \n", st);
            break;
        }
    }

    g_io_channel_shutdown (channel, TRUE, &error);
    close(fd);

    return 0;
}

运行结果:

[root@centos7_6 build]# ./glib_iochannel_file
read_line: NAME="CentOS Linux"

read_line: VERSION="7 (Core)"

read_line: ID="centos"

(中间省略部分运行结果,不影响阅读)

read_line: REDHAT_SUPPORT_PRODUCT="centos"

read_line: REDHAT_SUPPORT_PRODUCT_VERSION="7"

read_line:

read error: 2!
[root@centos7_6 build]#
IO通道对象添加到主循环

IO通道支持事件源添加到主循环。下面演示捕获标准输入的字符串,且反向后再输出到标准输出。
为了使程序在自动化测试时可以自动退出,增加了一个超时机制,当时间到10秒后,无论是否在操作,均退出程序(可以优化为:检测到无任何输入后10秒才退出)。
示例代码如下:
源码见glib_examples\glib_iochannel\glib_iochannel_mainloop

#include <glib.h>

GMainLoop *loop = NULL;

gboolean io_channel_callback(gpointer data)
{
    GIOChannel *channel = NULL;(GIOChannel *)data;
    gchar *str = NULL;
    gsize len = 0;

    channel = (GIOChannel *)data;
    g_return_if_fail(channel);

    //从stdin读取一行字符串
    g_io_channel_read_line(channel, &str, &len, NULL, NULL);

    //去掉回车键()
    while(len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
        str[--len]='\0';

    g_print("reverse str: \n");
    //反转字符串
    for(;len;len--) {
        g_print("%c",str[len-1]);
    }
    g_print("\n");
    
    //判断结束符
    if(strcasecmp(str, "q") == 0){
        g_main_loop_quit(loop);
    }
    g_free(str);
}

static gboolean timeout_cbk (gpointer user_data)
{
    g_print("10 seconds have passed, timeout to quit! \n");

    g_main_loop_quit((GMainLoop *)user_data);

    return FALSE;
}

gint main (gint argc, gchar **argv)
{
    GMainContext *context = NULL;
    GSource *io_source = NULL;
    GSource *tm_source = NULL;
    GIOChannel *channel = NULL;

    context = g_main_context_new();
    g_return_if_fail(context);

    loop = g_main_loop_new(context, TRUE);
    g_return_if_fail(loop);

    channel = g_io_channel_unix_new(1);
    g_return_if_fail(channel);

    io_source = g_io_create_watch(channel, G_IO_IN);
    g_io_channel_unref(channel);
    g_source_set_callback(io_source, io_channel_callback, channel, NULL);

    g_source_attach(io_source, context);
    g_source_unref(io_source);

    tm_source = g_timeout_source_new(10*1000);
    g_source_set_callback(tm_source, timeout_cbk, loop, NULL);
    g_source_attach(tm_source, context);
    g_source_unref(tm_source);


    g_print("please input some words(q to quit, or wait 10s for timeout): \n");
    g_main_loop_run(loop);

    g_main_loop_unref(loop);

    return 0;
}

运行结果:
超时退出效果

[root@centos7_6 build]# ./glib_iochannel_mainloop
please input some words(q to quit, or wait 10s for timeout):
abcd
reverse str:
dcba
123456
reverse str:
654321
10 seconds have passed, timeout to quit!

输入q退出程序效果

[root@centos7_6 build]# ./glib_iochannel_mainloop
please input some words(q to quit, or wait 10s for timeout):
abcd
reverse str:
dcba
123456
reverse str:
654321
q
reverse str:
q
[root@centos7_6 build]#
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值