#include <stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <stdlib.h>
char *dev="/dev/ttyUSB0";
int OpenDev(char *Dev)
{
int fd = open( Dev, O_RDWR | O_NOCTTY | O_NDELAY);
if (-1 == fd) {
perror("Can't Open Serial Port");
return -1;
} else
return fd;
}
int read_fun(int fd,char *buf ,int len){
int tem = read(fd,buf,len);
printf("read:%s\n",buf);
return tem;
}
int write_fun(int fd,char *buf ,int len){
return write(fd,buf,len);
}
int main(){
char *write_buf = "hello";
char *read_buf = (char *)malloc(20);
int fd;
fd_set set;
pid_t pid;
fd = OpenDev(dev);
printf("fd is %d\n",fd);
while(1){
FD_ZERO(&set);
FD_SET(fd, &set);//此处将读取的串口fd加入队列
pid = fork();
if(pid == 0){
while(1){
select(fd+1,&set,NULL,NULL,NULL);//此次判断读取的队列
if(FD_ISSET(fd, &set)){ /*测试读取fd是否在set集合中*/
read_fun(fd,read_buf,20);
}
}
}else{
while(1){
int write_tem = write_fun(fd,write_buf,sizeof(write_buf));
printf("write %d bytes\n",write_tem);
sleep(5);
}
}
}
}
需要在串口处将收发短接,才能收到数据