c read() causing bad file descriptor error -
context program reading through filestream, 4k chunks @ time, looking pattern. starts reading in 4k, , if doesn't find pattern there, starts loop reads in next 4k chunk (rinse , repeat until eof or pattern found). on many files code working properly, files getting errors.
the code below highly redacted, know might annoying, includes lines reference file descriptor or file itself. know don't want take word it, since i'm 1 problem...
having done little homework before crying help, i've found:
the file descriptor happens = 6 (it's 6 files working), , number isn't getting changed through life of execution. don't know if that's useful info or not.
by inserting print statements after every operation accesses file descriptor, i've found successful files go through following cycle "open-read-close-close" (i.e. pattern found in first 4k) unsuccessful files go "open-read-read error (bad file descriptor)-close." no premature close, , it's getting in first read successfully, second read causes bad file descriptor error.
.
int function(char *file) { int len, fd, go = 0; char buf[4096]; if((fd = open(file, o_rdonly)) <= 0) { my_error("error opening file %s: %s", file, strerror(errno)); return null; } //first read if((len = read(fd, buf, 4096)) <= 0) { my_error("error reading file %s: %s", file, strerror(errno)); close(fd); return null; } //pattern-searching if(/*conditions*/) { /* found it, no need keep looking*/ close(fd); } else { //reading loop while(!go) { if(/*conditions*/) { my_error("cannot locate pattern in file %s", file); close(fd); return null; } //next read if((len = read(fd, buf, 4096)) <= 0) /**** fails here *****/ { my_error("error reading file, possible bad message %s: %s", file, strerror(errno)); close(fd); return null; } if(/*conditions*/) { close(fd); break; } //pattern searching if(/*conditions*/) { /* found pattern */ go++; //break out of while loop //stuff close(fd); } else { //stuff, , loop again next chunk } } /*end while loop*/ }/*end else statement*/ close(fd); }
.
try not worry pattern-reading logic - operations done on char buffer, not on file, ought have no impact on problem.
eof returns 0 (falls if ... <= 0), not set errno, may have out of date code in it.
try testing 0 , negative (error, -1) values seperately.
regarding "strace": i've used little @ home, , in previous jobs. unfortunately, it's not installed in current work environment. useful tool, when it's available. here, took "let's read fine manual" (man read) approach questioner :-)
Comments
Post a Comment