阻塞与非阻塞
程序员文章站
2024-01-13 18:32:10
...
阻塞的概念
read函数在读设备或者读管道,或者读网络的时候,
设置非阻塞
#include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <string.h>
6 #include <sys/types.h>
7
8
✹ 9 int main(int argc, char *argv[])
10 {
11 // int fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
12 int fd = open("dev/tty", O_RDWR);
13 // fcntl() 函数 设置非阻塞
14 int flags = fcntl(fd, F_GETFL);
15 flags |= O_NONBLOCK;
16 fcntl(fd, F_SETFL, flags);
17
18 char buf[256];
19 int ret = 0;
20 while (1)
21 {
22 ret = read(fd, buf, sizeof(buf));
23 if (ret < 0)
24 {
25 perror("read err:");
26 printf("ret is %d\n", ret);
27 }
28 if (ret)
29 {
30 printf("buf is %s\n", buf);
31 }
32 printf("haha\n");
33 sleep(1);
34 }
35 close(fd);
36 return 0;
37 }