当进程调用一个阻塞的系统函数时,该进程被置于睡眠(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是根据需要添加的处理程序。