【Linux系统编程】阻塞和非阻塞

阻塞和非阻塞描述的是线程的状态

同步异步描述的是编程的方式

●阻塞:调用函数的结果返回前,当前进程(线程)会被挂起,直到得到结果才会继续运行。

●非阻塞:调用函数后会直接返回结果,不会等待结果。

open()打开文件时可以通过参数O_NONBLOCK设置文件为非阻塞模式:

        普通文件默认是非阻塞的,内核缓冲区保证了普通文件IO不会发生阻塞事件,所以普通文件不需要考虑是否阻塞

        设备、管道和套接字默认是阻塞的,以O_NONBLOCK方式打开可以做非阻塞IO (NonblockI/O)

阻塞模式标准输入:

char buf [ 1024];
int read_count = read(0, buf, sizeof (buf));
printf("read count = %d\n", read_count);
write(1, buf, read_count);

非阻塞模式打开终端:

char buf [ 1024];
int read_count = read(0, buf, sizeof (buf));
printf("read count = %d\n", read_count);
write(1, buf, read_count);

perror会把errno对应的报错信息给打出来

#include<stdio.h>  
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<errno.h>

int main(int argc, char* argv[])
{
    int fd = open("dev/fd/0", O_RDWR | O_NONBLOCK);
	char buf[1024];
	int read_count = read(fd, buf, sizeof(buf));
	printf("read_count = %d, errno = %d\n", read_count, errno);
	
    return 0;
}


 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值