Non-blocking read serial terminal data

When a process calls a blocking system function, the process is placed in a sleep (Sleep) state, and the kernel schedules other processes to run until the event that the process is waiting for occurs. It is possible to continue to run. The opposite of the sleep state is the Running state. Open the terminal and use the O_NONBLOCK flag to achieve non-blocking reading of terminal data:

#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;
}
where your_operations_a, your_operations_b are handlers added as needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325666799&siteId=291194637