非阻塞输出

mz126 mz126 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
以下是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;
}
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
mz126
C语言 70,039 成员 243,237 内容