سؤال

I am trying to write a program that uses the mmap function in C to read a file, map the contents of the file to memory, and (for now) output the first character in the file. I have written the code below, and all is well up until the last line, where I attempt to print the character. At that point, the program outputs Bus error (core dumped).

What could be going wrong with this program? I followed this tutorial and I don't appear to have done anything that would lead to it not working. For reference, the file I am reading in contains one line: "The quick brown fox jumped over the lazy dog". I want to make sure my program is correct before working on additional functionality, so I would expect the output to be the first character, "T".

/* open file */
file = open(fileName, O_RDONLY);

/* check if file exists */
if (file == -1) {
    printf("File not found\n");
    return 1;
}

/* get page size */
pageSize = getpagesize();

/* map file to memory */
data = mmap((caddr_t)0, pageSize, PROT_READ, MAP_SHARED, file, pageSize);

/* check if map was successful */
if (data == (caddr_t)(-1)) {
    printf("mmap error\n");
    return 1;
}

printf("%c\n", data[0]);
هل كانت مفيدة؟

المحلول

You're using an offset of pageSize, meaning you're trying to map starting with the second page of the file. Since your file is small, this is off the end of the file and you get a bus error.

Change offset to 0 and it should work as you expect.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top