I asked this question about how to read a text file starting from offset pos
to offset end
through mmap()
. In particular the text file is read by multiple threads with the following code:
void getNextKeyValue() {
key = pos;//value is the actual file offset
char *mmappedData = (char*) mmap(NULL, end-pos+1, PROT_READ, MAP_PRIVATE , fd, pos);
assert(mmappedData != NULL);
value.assign(mmappedData);
assert(munmap(mmappedData, end-pos+1)==0);
morePairs = false;
}
The unreported variables are declared and initialized somewhere else. What By the way, the following code read the whole text file, and not from offset pos
to end
.
In addiction, the program terminates abruptly (no error output) with multiple threads, while it terminates correctly with only one thread that read the whole file.
UPDATE:
Following this example (you can try my version, using cout
insted of write
, HERE with ./main main.cpp 10 20
) I found out that what I was doing wrong was that I printed the read data through cout<<mmappedData<<endl
. Insted if I use write(STDOUT_FILENO, mmappedData+pos-pa_offset, end-pos);
the right portion of text is printed.
What I still do not understand is why the whole text is stored inside mmappedData
(or addr
following the linked example): the mmap
usage clearly states that the number of bytes read are the 2nd arg starting from the 4th arg.