Hi Guys,
I am trying to learn how the select function works. The code below seems to work on the serial side. But not on the stdin side. Any ideas ?
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyUSB0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
#define MAXLINE 50
#ifndef max
#define max( a, b ) ( ((a) > (b)) ? (a) : (b) )
#endif
#ifndef min
#define min( a, b ) ( ((a) < (b)) ? (a) : (b) )
#endif
void handle_input_from_fd1(int fd1);
volatile int STOP=FALSE;
main()
{
struct termios oldtio,newtio;
char input[MAXLINE];
int fd1; /* input sources 1 and 2 */
fd_set readfs; /* file descriptor set */
int maxfd; /* maximum file desciptor used */
fd1 = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd1 <0) {perror(MODEMDEVICE); exit(-1); }
FD_ZERO(&readfs);
tcgetattr(fd1,&oldtio); /* save current port settings */
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
// set input mode (non-canonical, no echo,...)
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0; // inter-character timer unused
newtio.c_cc[VMIN] = 1; // blocking read until 5 chars received
tcflush(fd1, TCIFLUSH);
tcsetattr(fd1,TCSANOW,&newtio);
//loop for input
while (1) {
FD_SET(fd1, &readfs); // set testing for source 1
FD_SET(fileno(stdin), &readfs); // set testing for source 2
maxfd = max(fileno(stdin), fd1)+1; // maximum bit entry (fd) to test
/* block until input becomes available */
select(maxfd, &readfs, NULL, NULL, NULL);
if (FD_ISSET(fd1,&readfs)) // input from source 1 available
handle_input_from_fd1(fd1);
if (FD_ISSET(fileno(stdin),&readfs)) // input from source 2 available
//handle_input_from_fd2(stdin,fd1);
{
if (fgets(input,MAXLINE,stdin) == NULL)
{
return; /* all done */
}
printf("input is: [%s]",input);
write(fd1, input,MAXLINE);
}
}
tcsetattr(fd1,TCSANOW,&oldtio);
}
void handle_input_from_fd1(int fd1)
{
int res;
char buf[255];
// while (STOP==FALSE) { /* loop for input */
res = read(fd1,buf,255); /* returns after 5 chars have been input */
buf[res]='\0'; /* so we can printf... */
//printf(":%s:%d\n", buf, res);
printf("%s", buf);
//if (buf[0]=='z') STOP=TRUE;
//}
}