read什么时候阻塞?阻塞有什么表现?

read(stdin, buf, size);

printf(“hello”);

如果read是阻塞的则会停止到read语句不会执行下一个语句;否则不会停止,会执行下一个语句。

#include    <stdio.h>
#include    <stdlib.h>
 
 #define     COUNT  10
 int
 main()
 {
    char    buf[COUNT];
    size_t  nbytes;
     int     n;
  
     for (n = 0; n< COUNT; n++)
         buf[n] = 0;
  
     nbytes = 10;
     read(stdin, buf, nbytes);
  
     printf("hello\n");
     printf("%s\n", buf);
 }


这个标准输入,我想应该是会阻塞的,结果是没有阻塞:


没有停止等待输入就直接输出了。这是有问题的,stdin是指针类型而read要求用int型的参数。

最后,改成:

#include    <stdio.h>
#include    <unistd.h>
#include    <stdlib.h>
#include    <fcntl.h>
 
#define     COUNT  10
int
main()
{
    char    buf[COUNT];
    size_t  nbytes;
    int     n, flags;


    for (n = 0; n< COUNT; n++)
        buf[n] = 0;


    if ( (flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
    {
        printf("F_GETFL error");
        exit(0);
    }
    
    printf("flags:%d\n", flags);


    nbytes = 10;
    read(STDIN_FILENO, buf, nbytes); 
    printf("hello\n");
    printf("%s\n", buf);
}


结果:

设置nonblock选项后:

#include    <stdio.h>
#include    <unistd.h>
#include    <stdlib.h>
#include    <fcntl.h>
 
#define     COUNT  10
int
main()
{
    char    buf[COUNT];
    size_t  nbytes;
    int     n, flags;
    int     fd;


    fd = 0;


    for (n = 0; n< COUNT; n++)
        buf[n] = 0;


    if ( (flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
    {
        printf("F_GETFL error");
        exit(0);
    }
    
    printf("flags old:%d\n", flags);


    flags |= O_NONBLOCK;
    if (fcntl(STDIN_FILENO, F_SETFL, flags) < 0)
    {
        printf("F_SETFL error");
        exit(0);
    }
    
    printf("flags new:%d\n", flags);




    nbytes = 10;
    read(STDIN_FILENO, buf, nbytes); 
    printf("hello\n");
    printf("%s\n", buf);
}


结果:



结果就像我想的那样。read阻塞的话会停止不进行,而非阻塞的话将不等待从stdin读取数据这个动作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值