使用mmap时,整数存储为不正确的值

问题描述 投票:0回答:1

我正在编写一个程序,该程序将使用mmap将结构数组写入文件。问题是第三个整数值(左)未正确存储。通过od查看文件时,left中的字节似乎向左移了一个字节。例如...

|loc            |value  |left          |right          |extra bytes?
001 000 000 000 103 120 000 000 000 003 000 000 000 004 000 000 //expected
001 000 000 000 103 120 000 000 003 000 000 000 004 000 000 000 //result
typedef struct{
    int32_t loc;
    char value[2];
    int32_t left;
    int32_t right;

}Node;

Node newNode(int i);

int main(int argc, char *argv[])
{
    int i;
    int fd;
    int result;
    Node *map;  /* mmapped array of int's */

    int filesize = strtol(argv[2], NULL, 10) * sizeof(Node);
    int numvalues = filesize / sizeof(Node);

    fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
    if (fd == -1) {
        perror("File failed to open");
        exit(1);
    }

    //I dont know why this makes it work but we need to move the file pointer around for some reason.
    result = lseek(fd, filesize-1, SEEK_SET);
    if (result == -1) {
        close(fd);
        perror("Error calling lseek()");
        exit(2);
    }

    // same with this
    result = write(fd, "", 1);

    /* Now the file is ready to be mmapped.
    */
    map = (Node *) mmap(0, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (map == MAP_FAILED) {
        close(fd);
        perror("Error mmapping the file");
        exit(4);
    }


    for (i = 0; i <numvalues; ++i) {
        map[i] = newNode(i);         /* here is where I save the data */
    }

    munmap(map, filesize);
    close(fd);
    return 0;
}

Node newNode(int i) { /*This method is where the structs are made*/
    Node n;
    n.left = i * 2 + 1;
    n.right = i * 2 + 2;
    n.value[0] = (char)(rand() % ('A' - 'Z') )+ 'A';
    n.value[1] = (char)(rand() % ('A' - 'Z') )+ 'A';
    n.loc = i;

    printf("%d, %d, %c, %c, %d\n", n.left, n.right, n.value[0], n.value[1], n.loc);

    return n;
}

此外,为什么将某些整数保存为小端,而另一些保存为大端。

c binaryfiles mmap
1个回答
0
投票

您遇到了两个问题:Endianess和struct padding。

Endianess

看来您的系统是小端的。这意味着最低有效字节将首先存储。我们可以看到1被存储为01 00 00 00的事实。在大端序系统中,它将为00 00 00 01。这意味着您的“预期”结果不正确。应该如下。请注意,左右字节已交换。

|loc            |value  |left          |right          |
001 000 000 000 103 120 003 000 000 000 004 000 000 000    

结构包装

所以您为什么没有获得上述预期结果?因为编译器在结构中添加了用于单词对齐的填充。因此,在value字段之后有两个填充字节。打印sizeof(Node)即可看到。因此,实际上所有内容都右移了两个字节。因此,实际的预期结果是:

|loc            |value  |pad     |left           |right          |
001 000 000 000 103 120  000 000 003 000 000 000 004 000 000 000    

这正是您所显示的实际结果。

© www.soinside.com 2019 - 2024. All rights reserved.