赞
踩
阻塞、非阻塞: 是设备文件、网络文件的属性。(文件)
阻塞读终端:默认情况下设备文件和网络文件是阻塞的。
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
-
-
- int main(void)
- {
- char buf[10];
- int n;
-
- n = read(STDIN_FILENO, buf, 10); // #define STDIN_FILENO 0 STDOUT_FILENO 1 STDERR_FILENO 2
- if(n < 0){
- perror("read STDIN_FILENO");
- exit(1);
- }
- write(STDOUT_FILENO, buf, n);
-
- return 0;
- }

非阻塞读终端 :一直读取,终端一直占用。
当读取设备文件(网络文件)的时候,返回值是-1: 并且 errno = EAGIN 或 EWOULDBLOCK, 说明不是read失败,而是read在以非阻塞方式读一个设备文件(网络文件),并且文件无数据。
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- int main(void)
- {
- char buf[10];
- int fd, n;
-
- fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
- if (fd < 0) {
- perror("open /dev/tty");
- exit(1);
- }
-
- tryagain:
-
- n = read(fd, buf, 10);
- if (n < 0) {
- if (errno != EAGAIN) { // if(errno != EWOULDBLOCK)
- perror("read /dev/tty");
- exit(1);
- } else {
- write(STDOUT_FILENO, "try again\n", strlen("try again\n"));
- sleep(2);
- goto tryagain;
- }
- }
-
- write(STDOUT_FILENO, buf, n);
- close(fd);
-
- return 0;
- }

非阻塞读终端和等待超时:设置一个超时。
- #include <unistd.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <errno.h>
- #include <string.h>
-
- #define MSG_TRY "try again\n"
- #define MSG_TIMEOUT "time out\n"
-
- int main(void)
- {
- char buf[10];
- int fd, n, i;
-
- fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
- if(fd < 0){
- perror("open /dev/tty");
- exit(1);
- }
- printf("open /dev/tty ok... %d\n", fd);
-
- for (i = 0; i < 5; i++){
- n = read(fd, buf, 10);
- if (n > 0) { //说明读到了东西
- break;
- }
- if (errno != EAGAIN) { //EWOULDBLOCK
- perror("read /dev/tty");
- exit(1);
- } else {
- write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
- sleep(2);
- }
- }
-
- if (i == 5) {
- write(STDOUT_FILENO, MSG_TIMEOUT, strlen(MSG_TIMEOUT));
- } else {
- write(STDOUT_FILENO, buf, n);
- }
-
- close(fd);
-
- return 0;
- }
-

产生阻塞的场景。 读设备文件。读网络文件。(读常规文件无阻塞概念。)
/dev/tty -- 终端文件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。