|
大家好,我最近在做一个串口数据转发到TCP端口的程序,现在假设有两条线程,一条从串口采集数据,另一条将采集到的数据发送到一个已经连接上的客户端,我应该怎样才能实现当串口有接收到数据时,另一条线程才发送数据,比如用一个全局的temp数组来保存数据。
我应该怎么做呢?再谢谢大家了,我编程实在不是很强。下面是代码的一部分,grab用来采集数据,service用来发送数据,请朋友们帮我改改,让从串口读到的数据能够转发到TCP端口,在下真的感激不尽。
void
grab(void)
{
recvbuf = (unsigned char *)malloc(1024);
recvdata = (unsigned char *)malloc(1024);
unsigned char comid[20];
int fd,n_read;
int recvlen=0;
temp = (unsigned char *)malloc(1024);
fd_set readfds;
int k,i=0,tt;
sprintf(comid,"/dev/ttyS0");
fd = OpenDev(comid);
if (fd>0)
set_speed(fd,57600);
else {
printf("Can't Open Serial Port!\n");
exit(1);
}
if (set_Parity(fd,8,1,'N')== FALSE) {
printf("Set Parity Error\n");
exit(1);
}
while(1) {
n_read = 0;
recvlen = 0;
printf("57600 8 1 N\n");
memset((recvbuf),0,sizeof(recvbuf));
memset((recvdata),0,sizeof(recvdata));
FD_ZERO(&readfds);
FD_SET(fd,&readfds);
while(1) {
if(select(fd+1,&readfds,NULL,NULL,NULL)>0) {
if(FD_ISSET(fd,&readfds))
{
if((n_read =read(fd,recvbuf,1024))==-1)
{
printf("no read data \n");
break;
}
else
{
for(k=0;k<n_read;k++)
{
memcpy(recvdata+recvlen+k,recvbuf+k,31);
}
recvlen=recvlen+n_read;
if(recvlen<31)
{
continue;
}
}
break;
}
break;
}
break;
}
printf("recvdata=");
for(tt=0;tt<31;tt++){
printf("%02X ",recvdata[tt]);
}
printf("\n");
printf("test %d\n",i++);
}
}
void
service(void *sockfd)
{
int *id=(int*) sockfd;
int sock;
sock = *id;
while((send(sock,recvdata,1024, 0) != -1)) {
continue;
}
close(sock);
pthread_exit(NULL);
} |
|