Unix Network Programming Episode 102

    
    if(FD_ISSET(STDIN_FILENO, &rset))
    {
        if((n=read(STDIN_FILENO, toiptr, &to[MAXLINE]-toiptr))<0)
        {
            if(errno!=EWOULDBLOCK)
                err_sys("read error on stdin");
        }
    }
    else if(n==0)
    {
        fprintf(stderr, "%s: EOF on stdin\n", gf_time());
        stdineof=1;
        if(tooptr==toiptr)
            Shutdown(socfd, SHUT_WR);
    }
    else
    {
        fprintf(stderr, "%s: read %d bytes from stdin\n",gf_time(),n);
        toiptr+=n;
        FD_SET(sockfd, &wset);
    }

    if(FD_ISSET(socfd, &rset))
    {
        if((n=read(sockfd, friptr, &fr[MAXLINE]-friptr))<0)
            if(errno!=EWOULDBLOCK)
                err_sys("read error on socket");
    }
    else if(n==0)
    {
        fprintf(stderr, "%s: EOF on socket\n", gf_time());
        if(stdineof)
            return;
        else
            err_quit("str_cli: server terminated prematurely");
    }
    else
    {
        fprintf(stderr, "%s: read %d bytes from socket\n", gf_time(), n);
        fprintf+=n;
        FD_SET(STDOUT_FILENO, &wset);
    }

str_cli function, second part: reads from standard input or socket

    if(FD_ISSET(STDOUT_FILENO, &wset)&&((n=friptr-froptr)>0))
    {
        if((nwritten=write(STDOUT_FILENO, froptr, n))<0)
        {
            if(errno!=EWOULDBLOCK)
                err_sys("write error to stdout");
        }
        else
        {
            fprintf(stderr, "%s: wrote %d bytes to stdout\n", gf_time(), nwritten);
            froptr+=nwritten;
            if(froptr==friptr)
                froptr=friptr=fr;
        }
    }

    if(FD_ISSET(sockfd, &wset)&&((n=toiptr-tooptr)>0))
    {
        if((nwritten=write(sockfd, tooptr, n))<0)
        {
            if(errno!=EWOULDBLOCK)
                err_sys("write error to socket");
        }
        else
        {
            fprintf(stderr, "%s: wrote %d bytes to socket\n", gf_time(), nwritten);
            tooptr+=nwritten;
            if(tooptr==toiptr)
            {
                toiptr=tooptr=to;
                if(stdineof)
                    Shutdown(sockfd, SHUT_WR);
            }
        }
    }

str_cli function, third part: writes to standard output or socket

#include "unp.h"
#include <time.h>

char *gf_time(void)
{
    struct timeval tv;
    static char str[30];
    char *ptr;

    if(gettimeofday(&tv, NULL)<0)
        err_sys("gettimeofday error");
    
    ptr=ctime(&tv.tv_sec);
    strcpy(str, &ptr[11]);

    snprintf(str+8, sizeof(str)-8, ".%06ld", tv.tv_usec);

    return str;
}

gf_time function: returns pointer to time string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值