非阻塞输出

C语言 码拜 9年前 (2015-05-11) 1007次浏览 0个评论
 

以下是linux c 一站式编程的一个例子,小弟照着打了一遍 ,运行的时候发现输入怎么样都无法跳出循环 求大神指导

#include <unistd.h>		// for read and write
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define  MSG_TRY  "try again\n"

int main( void )
{
	char buf[10];
	int fd , readn;
	fd = open( "/dev/tty" , O_RDONLY | O_NONBLOCK );

	if( fd < 0 )
	{
		perror( "open /dev/tty" );
		exit(1);
	}

tryagain:
	readn = read( fd , buf , 10 );
	if( readn < 0 )
	{
		if( errno == EAGAIN )
		{
			sleep(3);
			write( STDOUT_FILENO , MSG_TRY , strlen(MSG_TRY) );
			goto tryagain;
		}
		else
		{
			perror("read /dev/tty");
			exit(1);
		}

	}

	write( STDOUT_FILENO , buf , readn );
	close(fd);
	return 0;
}
20分
按Ctrl+D

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明非阻塞输出
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!