I am writing code to read from the serial port on my linux machine. I go through the initialization and then when i call read(fd...) in the main function I can read the data correctly. Once I try to pass the fd to another function, so main is short and sweet, the data i get is garbage. I have been struggling with this error for so long that I have even tried doing all the init and reading in the function I want to handle the data and after everything is initialized properly, the read still gives me garbage.
I have printed out both file descriptors before I do my read and they are the same value. So is there something else that is the reason behind my issue?Code:void sample(int fd) { int i; char* buf = (char*)malloc(128); for(i=0;i<100;i++) { read(fd, buf, 1); printf("%s", buf); fflush(stdout); } } // sample int init(int* fd) { struct termios oldtio, newtio; *fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY); if (*fd <0) { perror(MODEMDEVICE); exit(-1); } tcgetattr(*fd,&oldtio); /* save current modem settings */ newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; 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); return(1); } // init int main( int argc , char * argv[] ) { int fd; char* buf = (char*)malloc(128); if (!init(&fd)) return 1; for(i=0;i<100;i++) { read(fd, buf, 1); printf("%s", buf); fflush(stdout); } // works sample(fd); // fails close(fd); } // main
Thanks,
Chris



LinkBack URL
About LinkBacks



