Linux 文件操作中的阻塞和非阻塞操作


//源代码
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>

char buffer[4096];
int main(int argc,char **argv)
{
       int delay = 1, n, m = 0;
      
       if(argc > 1)
       {
             delay = atoi(argv[1]);
             printf("delay = %d seconds\n", delay);
       }
       fcntl(0,F_SETFL,fcntl(0,F_GETFL)|O_NONBLOCK);//stdin
       fcntl(1,F_SETFL,fcntl(1,F_GETFL)|O_NONBLOCK);//stdout
      
       while(1)
       {
             n = read(0,buffer,4096);
             if (n > 0)
             {
                   printf("Got %d byte data.\n", n);
             }
             if (n>0)
                   m = write (1,buffer,n);
             if ((n<0||m<0) && (errno != EAGAIN))
                   break;
             if ((n<0||m<0) && (errno == EAGAIN))
             {
                 perror( n<0 ? "stdin working in NONBLOCK, no data!" : "stdout working in NONBLOCK, no data");
             }
             sleep(delay);
       }
       perror( n<0 ? "stdin" : "stdout");
       exit(1);
}
执行:
[root@localhost nbtest]# ./nbtest 5
delay = 5 seconds
stdin working in NONBLOCK, no data!: Resource temporarily unavailable
12345
Got 6 byte data.
12345
注意,
(1)在标准输入中键入回车后才算是有效输入。
(2)回车也算是输入的一个字符,比如输入12345+回车,实际读入的长度是6个字节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值