unix/linux编程实践教程------学习笔记(第二章)

本文详细介绍了通过建立内存缓冲池来优化从UTMP_FILE文件读取登录信息的过程,减少了系统调用次数,显著提高了程序效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第2.7节   提高文件i/o效率的方法-----使用缓冲

在上一节编写who程序的过程中,我们词用的方法是从UTMP_FILE文件中每次读取sizeof(struct utmp)大小的数据,也就是每次读取一个结构体大小的登录信息。那么这样读取的效率非常低。这一节,我建立一个内存池,每次读取16个结构体大小的数据,这样的话我的程序使用系统调用的次数就变少了很多,有助于提高程序效率。

程序如此

<pre name="code" class="cpp">/* utmplib.c  - functions to buffer reads from utmp file 
 *
 *      functions are
 *              utmp_open( filename )   - open file
 *                      returns -1 on error
 *              utmp_next( )            - return pointer to next struct
 *                      returns NULL on eof
 *              utmp_close()            - close file
 *
 *      reads NRECS per read and then doles them out from the buffer
 */
#include        <stdio.h>
#include        <fcntl.h>
#include        <sys/types.h>
#include        <utmp.h>

#define NRECS   16
#define NULLUT  ((struct utmp *)NULL)
#define UTSIZE  (sizeof(struct utmp))

static  char    utmpbuf[NRECS * UTSIZE];                /* 内存缓冲     */
static  int     num_recs;                               /* 数据数目   */
static  int     cur_rec;                                /* 当前数据指针   */
static  int     fd_utmp = -1;                           /* 保存登录信息文件描述符 */

utmp_open( char *filename )
{
        fd_utmp = open( filename, O_RDONLY );           /* open it      */
        cur_rec = num_recs = 0;                         /* no recs yet  */
        return fd_utmp;                                 /* report       */
}

struct utmp *utmp_next()
{
        struct utmp *recp;

        if ( fd_utmp == -1 )                            /* error ?      */
                return NULLUT;
        if ( cur_rec==num_recs && utmp_reload()==0 )    /* 当cur_rec等于num_recs时,说明当前缓冲区的数据已经读取完毕,&&号后面的函数开始执行,读取下一个缓冲区域的数据   */
                return NULLUT;
                                        /* get address of next record    */
        recp = ( struct utmp *) &utmpbuf[cur_rec * UTSIZE];
        cur_rec++;
        return recp;
}

int utmp_reload()
/*
 *      read next bunch of records into buffer
 */
{
        int     amt_read;

                                                /* read them in         */
        amt_read = read( fd_utmp , utmpbuf, NRECS * UTSIZE );   

                                                /* how many did we get? */
        num_recs = amt_read/UTSIZE;             /*当前读取数据的个数
                                                /* reset pointer        */
        cur_rec  = 0;                           
        return num_recs;
}

utmp_close()
{
        if ( fd_utmp != -1 )                    /* don't close if not   */
                close( fd_utmp );               /* open                 */
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值