速度征求答案 正确追加100分 2小时之内 谢谢
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#define BAUDRATE B115200
#define COM1 "/dev/ttyS0"
#define COM2 "/dev/ttyS1"
#define ENDMINITERM 27
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
volatile int fd;
void* keyboard(void * data)
{
int c;
for (;;){
c=getchar();
if( c== ENDMINITERM){
STOP=TRUE;
break ;
}
}
return NULL;
}
void* receive(void * data)
{
int c;
printf("read modem\n");
while (STOP==FALSE)
{
//在此处补充填写代码?实现读取串口数据、并将数据在标准终端上写出来
}
printf("exit from reading modem\n");
return NULL;
}
void* send(void * data)
{
int c='0';
printf("send data\n");
while (STOP==FALSE)
{
c++;
c %= 255;
//在此处补充填写代码?实现写入串口数据
usleep(1000000);
}
printf("exit from send modem\n");
return NULL;
}
int main(int argc,char** argv)
{
struct termios oldtio,newtio;
pthread_t th_a, th_b, th_c;
//在此处补充填写代码?实现打开串口1的功能
if (fd <0) {
perror(COM1);
exit(-1);
}
tcgetattr(fd,&oldtio);
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;/*ctrol flag*/
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
//在此处补充填写代码?实现创建键盘监控、接收、发送三个线程,并等待线程结束
tcsetattr(fd,TCSANOW,&oldtio); /*恢复串口设置*/
//在此处补充填写代码?实现关闭串口功能
exit(0);
}
參考答案:while (STOP==FALSE)
{
//在此处补充填写代码?实现读取串口数据、并将数据在标准终端上写出来
if(read(fd, data, ENDMINITERM)==0)
return data;
}
while (STOP==FALSE)
{
c++;
c %= 255;
//在此处补充填写代码?实现写入串口数据
if(write(fd, data, ENDMINITERM) < 0)
exit(1);
usleep(1000000);
}
//在此处补充填写代码?实现打开串口1的功能
fd = open(COM1,O_RDWR);
if(fd < 0)
exit(1);
//在此处补充填写代码?实现创建键盘监控、接收、发送三个线程,并等待线程结束 th_a, th_b, th_c;
if(pthread_create (&th_a, 0, keyboard, 0) != 0)
exit(1);
pthread_join(th_a,NULL);
if(pthread_create (&th_b, 0, receive, 0) != 0)
exit(1);
pthread_join(th_b,NULL);
if(pthread_create (&th_c, 0, send, 0) != 0)
exit(1);
pthread_join(th_c,NULL);
//在此处补充填写代码?实现关闭串口功能
close(fd);