📄 p3-6-7.c
字号:
#include <sys/types.h>#include <unistd.h>#include <fcntl.h>#include <stdio.h>#include "err_exit.h"#define STDIN_FILENO 0#define STDOUT_FILENO 1char buf[100000];/* 如果value非0,设置desc的O_NONBLOCK标志,否则清除该标志。成功返回0,失败返回-1.*/int set_nonblock_flag (int desc, int value){ int oldflags = fcntl(desc, F_GETFL, 0); /* 获取标签失败,返回错误指示. */ if (oldflags == -1) return -1; /* 形成我们需要的标签. */ if (value != 0) oldflags |= O_NONBLOCK; else oldflags &= ~O_NONBLOCK; /* 设置新标签. */ return fcntl(desc, F_SETFL, oldflags);}int main(void){ int totalbytes, nwrite; char *ptr; int ntimes = 0; /* 从标准输入一次读入100000字节数据 */ totalbytes = read(STDIN_FILENO,buf,sizeof(buf)); fprintf(stderr,"read %d bytes\n", totalbytes); /* 设置无阻塞I/O */ if (set_nonblock_flag(STDOUT_FILENO, 1) < 0) err_exit("set nonblock flag failed "); /* 将buf中的数据写至标准输出,直至全部写出 */ for (ptr = buf; totalbytes >0; ntimes++){ errno = 0; nwrite = write(STDOUT_FILENO,ptr, totalbytes); if (nwrite < 0){ fprintf(stderr,"%d nwrite = %d,error = %d, ",ntimes,nwrite,errno); perror(""); } else { fprintf(stderr,"%d nwrite = %d,error = %d\n",ntimes,nwrite,errno); ptr += nwrite; totalbytes -= nwrite; } } /* 恢复阻塞方式 */ if (set_nonblock_flag(STDOUT_FILENO, 0) < 0) err_exit ("clear nonblock flag failed"); exit(0);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -