码迷,mamicode.com
首页 > 其他好文 > 详细

分析EOF究竟是什么

时间:2015-01-26 08:54:16      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

EOF仅仅是一种状态或者说条件,需要触发。read调用遇到文件结尾,触发该条件,结果将返回0。针对EOF,对于标准输入设备,普通文件,管道文件,网络套接字文件是read如何触发呢?下面程序将说明:

server.c 是socket套接字服务端,目的为了网络套接字文件是read如何触发测试用的。

###########################server.c##############################
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>

int main()
{
 int connfd;
 struct sockaddr_in servadd;

 int sockfd=socket(AF_INET, SOCK_STREAM, 0);

 bzero(&servadd, sizeof(servadd));
 servadd.sin_family=AF_INET;
 servadd.sin_port=htons(9999);
 servadd.sin_addr.s_addr=inet_addr("192.168.60.136");
 socklen_t len = sizeof(servadd);

 socklen_t Reuseaddr = 1;
 setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &Reuseaddr, sizeof(Reuseaddr ) );

 bind(sockfd, (const struct sockaddr *)&servadd, len);

 listen(sockfd,8);

 while( (connfd = accept(sockfd,(struct sockaddr *)&servadd, &len)) >0)
 {
         printf("##########################\n");
         write(connfd,"abc",3);
 }
        return 0;
}


############################test.c############################
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <strings.h>
#define MAXSIZE 256
#define FNAME "test"
int main()
{

     char buf[MAXSIZE];
        int ret,pipefd[2];

        ret= read(0,buf,MAXSIZE);
        printf("standart input ret:%d\n",ret);

        int fd = open(FNAME,O_RDONLY|O_CREAT);
        ret= read(fd,buf,1);
        printf("regular file ret:%d\n",ret);
        close(fd);

        FILE *fp = fopen(FNAME, "r");
        ret = fread(buf,1,1,fp);
        printf("regular file ret:%d\n",ret);
        fclose(fp);

        pipe(pipefd);
        close(pipefd[1]);
        ret = read(pipefd[0],buf,1);
        printf("pipe file ret:%d\n",ret);

        int sockfd=socket(AF_INET, SOCK_STREAM, 0);
        struct sockaddr_in servadd;

        bzero(&servadd,sizeof(servadd));
        servadd.sin_family = AF_INET;

        servadd.sin_port = htons(9999);
        servadd.sin_addr.s_addr=inet_addr("192.168.60.136");

        connect(sockfd, (struct sockaddr *)&servadd, sizeof(servadd));
        ret = read(sockfd,buf,3);
        perror("err1");
        ret = read(sockfd,buf,3);
        printf("socket file ret2:%d\n",ret);
        perror("err2");

}
测试过程:
1.运行下列命令
#gcc server.c -o server
#gcc test.c -o test
#./server
#./test

输入ctrl+d键

standart input ret:0
regular file ret:0
regular file ret:0
pipe file ret:0
socket file ret1:3

err1: Success

#killall server

触发socket EOF

socket file ret2:0
err2: Success

2.分析
#man read
RETURN VALUE
       On success, the number of bytes read is returned (zero indicates end of file)
可见返回值为:0,已经触发了EOF,具体如何触发,参见程序.

分析EOF究竟是什么

标签:

原文地址:http://blog.csdn.net/zou128865/article/details/43147953

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!