本关的编程任务是补全右侧代码片段中Begin至End中间的代码,具体要求如下: 在 UartBlockRead 中,以阻塞的方式打开串口,并设置为5s的超时返回,然后从串口中读取数据,并返回读取数据的长度。 在 UartUnblockRead 中,以非阻塞的方式打开串口,从串口中读取数据,并返回读取数据的长度。 本关涉及的代码文件UartBlockTest.c的代码框架如下: #include <stdio.h> #include <sys/types.h> #include <unistd.h> int UartBlockRead (int fd, char *rbuf) { /*********Begin*******/ /**********End********/ } int UartUnblockRead (int fd, char *rbuf, int length) { /*********Begin*******/ /**********End********/
时间: 2023-07-05 10:24:36 浏览: 68
UartBlockRead 函数的代码如下:
```
int UartBlockRead (int fd, char *rbuf) {
int len = 0;
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
int retval = select(fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1) {
perror("select()");
} else if (retval) {
len = read(fd, rbuf, sizeof(rbuf));
} else {
printf("No data within 5 seconds.\n");
}
return len;
}
```
UartUnblockRead 函数的代码如下:
```
int UartUnblockRead (int fd, char *rbuf, int length) {
int len = 0;
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
int retval = select(fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1) {
perror("select()");
} else if (retval) {
len = read(fd, rbuf, length);
}
return len;
}
```