APUE 非阻塞I/O的学习

来源:互联网 发布:初恋怪兽 知乎 编辑:程序博客网 时间:2024/05/21 09:51

 #include <sys/types.h>
  2 #include <errno.h>
  3 #include <fcntl.h>
  4 #include "../../ourhdr.h"
  5
  6 char buf[100000];
  7
  8 int main()
  9 {
 10         int   ntowrite,nwrite;
 11         char  *ptr;
 12
 13         ntowrite = read(STDIN_FILENO, buf, sizeof    (buf));
 14         fprintf (stderr, "read %d bytes/n", ntowr    ite);

               set_fl(STDOUT_FILENO, O_NONBLOCK);
 15         /*set nonblocking*/
 16         for (ptr = buf; ntowrite > 0;)
 17         {
 18                 errno = 0;
 19                 nwrite = write(STDOUT_FILENO, ptr    , ntowrite);
 20                 fprintf (stderr, "nwrite = %d, er    rno = %d/n", nwrite, errno);
 21                 if (nwrite > 0)
 22                 {
 23                         ptr += nwrite;
 24                         ntowrite -= nwrite;
 25                 }
 26         }
 27
 28         clr_fl(STDOUT_FILENO, O_NONBLOCK);
 29         /*clear nonblocking*/
 30
 31         exit(0);
 32 }

#include <fcntl.h>
  2 #include "../../ourhdr.h"
  3
  4 void set_fl(int fd, int flags)
  5         /*flags are file status flags to turn on*    /
  6 {
  7         int val;
  8
  9         if ((val = fcntl (fd, F_GETFL, 0)) < 0)
 10                 err_sys("fcntl F_GETFL error");
 11
 12         val |= flags; /*turn on flags*/
 13
 14         if (fcntl (fd, F_SETFL, val) < 0)
 15                 err_sys("fcntl F_SETFL error");
 16 }
 #include <fcntl.h>
  2 #include "../../ourhdr.h"
  3
  4 void clr_fl(int fd, int flags)
  5 {
  6         int val;
  7         if ((val = fcntl (fd, F_GETFL, 0)) < 0)
  8                 err_sys("fcntl F_GETFL error");
  9
 10         val ^= flags; /*turn off flags*/
 11
 12         if (fcntl (fd, F_SETFL, 0) < 0)
 13                 err_sys ("fcntl F_GETFL error");
 14 }

 

下一个函数提供100000个字的文件,可以拿任何文件做实验,不过要字符够多100000个,呵呵

#include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5
  6 int main()
  7 {
  8         int fd;
  9         int i;
 10         char buf[20]="abcdefghijklmnopqrst";
 11         fd = open ("duxiao", O_RDWR|O_CREAT);
 12         for (i=0; i<50000; i++)
 13         write (fd, buf, 20);
 14 }
 15/*********************wenjian.c*******************************************

把wenjian.c生成的文件(例如testfile)

编译前面程序a.out

按照APUE上:

a.out < testfile > test

read 100000 bytes
nwrite = 100000, errno = 0
会生成一个test文件,然后:

a.out < testfile 2>test2

这个程序会在终端输出很多

生成的文件可以查看write频繁调用,并很多次调用出错

这就是说明非阻塞程序发出数千个WRITE调用,只有20个左右真正输出数据, 其余的出错返回,这种形式的循环称为轮询,在用户系统上浪费CPU时间,

set_fl(STDOUT_FILENO, O_NONBLOCK);这句程序,我们把标准输出的阻塞关掉啦;

 

 

原创粉丝点击