4. Use the fcntl function to complete non-blocking IO

You can use the fcntl function to change the properties of an open file, and you can reset the flags such as read, write, append, and non-blocking (these flags are called File StatusFlag) without having to re-open the file.

The following example uses the fcntl commands F_GETFL and F_SETFL to change the attributes of STDIN_FILENO and the O_NONBLOCK option to implement the function of non-blocking read terminals.

#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
Function:
   Change file attribute
parameters:
fd: file descriptor
cmd: set command
F_GETFL
F_SETFL
arg: optional, determined by the second parameter, such as no when get, there is a value when set
Return value:
file status flag  
-1: failure
step:
int flag; // file status flag 
flag = fcntl( sockfd, F_GETFL, 0); //read 
flag |= O_NONBLOCK;//change

fcntl(sockfd, F_SETFL, flag);//写

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

intmain()
{
	char buf[32] = {0};
	
#if 1
	int flag;
	flag = fcntl(0, F_GETFL, 0);
	flag |= O_NONBLOCK;
	fcntl(0, F_SETFL, flag);
#endif

	while(1)
	{
		gets(buf);
		printf("quit block\n");
		puts(buf);
		sleep(1);
	}
}

The running result is as follows:


Guess you like

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