非阻塞读取串口终端数据

当进程调用一个阻塞的系统函数时,该进程被置于睡眠(Sleep)状态,这时内核调度其它进程运行,直到该进程等待的事件发生了它才有可能继续运行。与睡眠状态相对的是运行(Running)状态。打开终端使用O_NONBLOCK标志,可以实现非阻塞读取终端数据:

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
	char buf[2];
	int fd, n;
	fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
	if(fd<0) 
	{
		printf("err:cant open serial port!");
		return -1;
	}

	for(;;)
	{
		n = read(fd, buf, 2);
		if(buf[0] == 'a')
		{
			your_operations_a();
		}
		if(buf[0] == 'b')
		{
			your_operations_b();
		}
	}
	
	close(fd);
	return 0;
}
其中your_operations_a, your_operations_b是根据需要添加的处理程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Marvin_wu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值