现在的位置: 首页 > 综合 > 正文

设置STDIN_FILENO为非阻塞模式

2018年04月03日 ⁄ 综合 ⁄ 共 437字 ⁄ 字号 评论关闭

Linux C:

 

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>

int main(void)
{
	char tmp[100];

	memset(tmp,0,sizeof(tmp));
	char str[] = "welcome to the linux world!";
	int len = strlen(str);
	printf("len = %d\n", len);
	fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);	// 设置为非阻塞形式

	while(1)
	{
		write(STDIN_FILENO, str, len);
		read(STDIN_FILENO, tmp, len);
		sleep(2);
		printf("%s\n", tmp);

	}
}

程序将会每隔2秒输出一句话:welcome to the linux world!

设置为非阻塞语句:fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);

抱歉!评论已关闭.