c - Unable to write the complete script onto a device on the serial port -
the script file has on 6000 bytes copied buffer.the contents of buffer written device connected serial port.however write function returns 4608 bytes whereas buffer contains 6117 bytes.i'm unable understand why happens.
{ file *ptr; long numbytes; int i; ptr=fopen("compass_script(1).4th","r");//opening script file if(ptr==null) return 1; fseek(ptr,0,seek_end); numbytes = ftell(ptr);//number of bytes in script printf("number of bytes in calibration script %ld\n",numbytes); //number of bytes in script 6117. fseek(ptr,0,seek_set); char writebuffer[numbytes];//creating buffer copy file if(writebuffer == null) return 1; int s=fread(writebuffer,sizeof(char),numbytes,ptr); //transferring contents buffer perror("fread"); fclose(ptr); fd = open("/dev/ttyusb3",o_rdwr | o_noctty | o_nonblock); //opening serial port speed_t baud=b115200; struct termios serialset;//setting baud rate communication tcgetattr(fd,&serialset); cfsetispeed(&serialset,baud); cfsetospeed(&serialset,baud); tcsetattr(fd,tcsanow,&serialset); long bytesw=0; tcflush(fd,tciflush); printf("\nnumbytes %ld",numbytes); bytesw=write(fd,writebuffer,numbytes); //writing script device connected serial port printf("bytes written%ld\n",bytesw);//only 4608 bytes written close (fd); return 0; }
well, that's specification. when write file, process blocked until whole data written. , means process run again when data has been written disk buffers. not true devices, device driver responsible of determining how data written in 1 pass. means that, depending on device driver, you'll data driven, part of it, or none @ all. depends on device, , how driver implements control.
on floor, device drivers have limited amount of memory fill buffers , capable of limited amount of data accepted. there 2 policies here, driver can block process until more buffer space available process it, or can return partial write only.
it's program resposibility accept partial read , continue writing rest of buffer, or pass problem client module , return partial write again. approach flexible one, , 1 implemented everywhere. have reason partial write, ball on roof, have decide next.
also, careful, use long ftell() function call return value , int fwrite() function call... although amount of data not huge , it's not probable values cannot converted long , int respectively, return type of both calls size_t , ssize_t resp. (like speed_t type use baudrate values) long can 32bit , size_t 64bit type.
the best thing can ensure whole buffer written code snippet next one:
char *p = buffer; while (numbytes > 0) { ssize_t n = write(fd, p, numbytes); if (n < 0) { perror("write"); /* driver signals error */ return 1; } /* writing 0 bytes weird, possible, consider putting * code here cope possibility. */ /* n >= 0 */ /* update pointer , numbytes */ p += n; numbytes -= n; } /* if here, have written numbytes */
Comments
Post a Comment