阻塞输出

mz126 2015-05-20 05:08:41
以下是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;
}
...全文
93 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lucifer_凡 2015-05-22
  • 打赏
  • 举报
回复
因为你设置了O_NONBLOCk,当你没有任何输入的时候肯定就会一直返回EAGAIN错误。

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧