- 论坛徽章:
- 0
|
该程序是APUE2第14章程序清单14-1
- #include "head.h"
- char buf[500000];
- int main(int argc, char** argv)
- {
- int nwrite, ntowrite;
- char *ptr = NULL;
- ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
- fprintf(stderr, "read %d bytes\n", ntowrite);
- set_fl(STDOUT_FILENO, O_NONBLOCK);
- ptr = buf;
- while(ntowrite > 0){
- errno = 0;
- nwrite = write(STDOUT_FILENO, ptr, ntowrite);
- fprintf(stderr, "nwrite = %d bytes, errno = %d\n", nwrite, errno);
- if(nwrite > 0){
- ntowrite -= nwrite;
- ptr += nwrite;
- }
- }
- clr_fl(STDOUT_FILENO, O_NONBLOCK);
- exit(0);
- }
- static int set_fl(int fd, int flags)
- {
- int val;
- val = fcntl(fd, F_GETFL, 0);
- if(val < 0){
- perror("fcntl get error");
- exit(1);
- }
- val |= flags;
- if(fcntl(fd, F_SETFL, val) < 0){
- perror("fcntl set error");
- exit(2);
- }
- return 0;
- }
- static int clr_fl(int fd, int flags)
- {
- int val;
-
- val = fcntl(fd, F_GETFL, 0);
- if(val < 0){
- perror("fcntl get error");
- exit(3);
- }
- val &= ~flags;
- if(fcntl(fd, F_SETFL, val) < 0){
- perror("fcntl clr error");
- exit(4);
- }
- return 0;
- }
复制代码
运行结果:
[xxxx@localhost chap14]$ ./a.out </etc/termcap >temp.file
read 500000 bytes
nwrite = 500000 bytes, errno = 0
[xxxx@localhost chap14]$ ./a.out </etc/termcap 2>stderr.out
[xxxx@localhost chap14]$ cat strerr.out
...............................
nwrite = -1 bytes, errno = 11
nwrite = -1 bytes, errno = 11
nwrite = -1 bytes, errno = 11
nwrite = -1 bytes, errno = 11
nwrite = -1 bytes, errno = 11
............................
nwrite = -1 bytes, errno = 11
nwrite = -1 bytes, errno = 11
nwrite = 109270 bytes, errno = 0
程序从标准输入中读取500000个字节的数据到进程缓冲区buf中,然后将标准输出设置为非阻塞模式,将buf缓冲区里的数据输出至标准输出
1.为什么当标准输出重定向到一个普通文件的时候,程序一次输出到文件成功,而当标准输出是终端时,为什么有write出现errno呢?
书中说:这个实例中,程序发出数千个write调用,但只有10-20个是真正输出数据的,其余的出错返回,这种形式的循环即轮询,在多
用户系统上它浪费CPU时间,这里“程序发出数千个write调用,但只有10-20个是真正输出数据的”不明白是怎么回事?
2. 书中说:虽然读写磁盘操作会使调用者短时间内阻塞,但不能将与磁盘操作有关的系统调用称为“低速”。
而低速系统调用是可能使进程永远阻塞的系统调用,read/write调用也可能使进程永远阻塞啊,难道read/write不是
低速系统调用吗? |
|