I have a very specific application where I need an auto-increment variable with persistent storage.
To be precise, I save the decimal representation of the int variable in a file. To generate the next number, I read() from the file, convert the contents back to int , add 1 and write() back to the file. I do not need simultaneous access to this data. Only one thread from one process calls functions to get the auto-increment number. The program works in an embedded environment where no one will have access to the console, so security should not be a concern. If that matters, it works on Linux 2.6.24 on MIPS.
The problem is that I do not get 100% reproducible results. Sometimes I get duplicate numbers, which is not acceptable for my application.
My implementation is as follows.
When starting the application, I have:
int fd = open("myfile", O_RDWR|O_CREAT|O_SYNC, S_IRWXU|S_IRWXG|S_IRWXO);
And auto zoom features:
int get_current(int fd) { char value[SIZE]; lseek(fd, 0, SEEK_SET); read(fd, value, SIZE); return atoi(value); } int get_next(int fd) { char value[SIZE]; int cur = get_current(fd); memset(value, 0, SIZE); sprintf(value, "%d", cur + 1); lseek(fd, 0, SEEK_SET); write(fd, value, SIZE); //fsync(fd); /* Could inserting this be the solution? */ return (cur + 1); }
I specifically missed the error checking above for the convenience of reading code. I have code to check the return values ββof all system calls.
The code was originally written by another person, and now that I have discovered this problem, the first step to solving it is to find out what might cause this. I am concerned that this could be due to file access caching. I know when I write() I have no guarantees, the data ever actually reached the physical medium, but is it safe to call read() without calling fsync() and still get predictable results? If so, then I have no ideas;)
Thanks for reading.
c linux
David
source share