c - 奇怪的 mmap 行为

标签 c mmap

我正在做一个实验,我有一个程序创建一个 16 字节的共享文件,然后每秒显示每个字节的值。

我希望能够在程序运行时更改文件,并让程序识别这些更改。

该程序似乎确实对内存进行了写入,也对文件进行了写入;但如果我在运行时修改该文件,尽管文件已更改,它仍会继续使用旧值,并且文件会停止更新。

这是无法识别更改的版本。

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

// | bag of global state.
struct {
    uint8_t *state;
    char *filename;
    int length;
} global = {
    (uint8_t *)0,
    "state.bin",
    16
};

// | clean up when ctrl-c is pressed.
static void onSIGINT(int unused)
{
    puts("caught SIGINT; cleaning up.");
    munmap(global.state, global.length);
    unlink(global.filename);
    exit(0);
}

// | display each byte of global shared memory
static void inspect()
{
    int i;

    for (i = 0; i < global.length; ++i) {
        printf("state[%d] = %d.\n", i, global.state[i]);
    }
}

int main(int argc, char **argv)
{
    /* anonymous scope: initialize shared memory */
    {
        // | mmap arguments
        void *addr = (void *)0;
        int prot = PROT_READ | PROT_WRITE;
        int flags = MAP_SHARED;
        int offset = 0;
        int fd = open(global.filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

        // | initialize memory to 16 zerod out bytes.
        uint8_t dummy[16];
        memset(&dummy, 0, global.length);
        write(fd, dummy, global.length);

        global.state = (uint8_t *)mmap (
            addr,
            global.length,
            prot,
            flags,
            fd,
            offset
        );

        if (global.state == MAP_FAILED) {
            close(fd);
            perror("could not create map.\n");
            unlink(global.filename);
        }                
    }

    signal(SIGINT, onSIGINT);

    /* anonymous scope: mainloop */
    {
        int count = 0;

        for (;;) {
            system("clear");
            printf("refresh number: %d.\n", count);
            ++count;
            inspect();
            sleep(1);
        }
    }

    return 0;
}

以下版本还会在每次显示迭代时递增每个字节,以表明它实际上正在使用共享文件。

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

// | bag of global state.
struct {
    uint8_t *state;
    char *filename;
    int length;
} global = {
    (uint8_t *)0,
    "state.bin",
    16
};

// | clean up when ctrl-c is pressed.
static void onSIGINT(int unused)
{
    puts("caught SIGINT; cleaning up.");
    munmap(global.state, global.length);
    unlink(global.filename);
    exit(0);
}

// | prints length bytes starting at address given.
static void inspect()
{
    int i;

    for (i = 0; i < global.length; ++i) {
        printf("state[%d] = %d.\n", i, global.state[i]);
        ++global.state[i];
    }
}

int main(int argc, char **argv)
{
    /* anonymous scope: initialize shared memory */
    {
        // | mmap arguments
        void *addr = (void *)0;
        int prot = PROT_READ | PROT_WRITE;
        int flags = MAP_SHARED;
        int offset = 0;
        int fd = open(global.filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

        // | initialize memory to 16 zerod out bytes.
        uint8_t dummy[16];
        memset(&dummy, 0, global.length);
        write(fd, dummy, global.length);

        global.state = (uint8_t *)mmap (
            addr,
            global.length,
            prot,
            flags,
            fd,
            offset
        );

        if (global.state == MAP_FAILED) {
            close(fd);
            perror("could not create map.\n");
            unlink(global.filename);
        }                
    }

    signal(SIGINT, onSIGINT);

    /* anonymous scope: mainloop */
    {
        int count = 0;

        for (;;) {
            system("clear");
            printf("refresh number: %d.\n", count);
            ++count;
            inspect();
            sleep(1);
        }
    }

    return 0;
}

请注意,它成功地不断增加每个字节,直到我更改 vim 中的一个字节为止。当我覆盖文件时,它会停止修改文件,但会继续从原来的位置开始计数。

为什么会这样;我怎样才能让它按预期工作?

最佳答案

这是由 vim 创建备份文件的方法引起的。这已记录在 backupcopy 中选项,典型的默认设置是重命名原始文件并编辑副本。这会导致内存映射 View 与备份关联,而不是与正在编辑的文件关联。

如果检查文件的 inode ,您会看到这种情况发生:

$ echo z>a && ls -i a
14551885 a
$ vim a
$ ls -i a
14551887 a

如您所见, inode 现在不同了。例如,如果您使用 python 打开并修改文件,您可以就地编辑文件,它将按预期工作。

使用 python 代替的示例:

$ ls -i a
14551886 a
$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('a', 'r+')
>>> f.write('22')
>>> f.close()
>>>

$ ls -i a
14551886 a

关于c - 奇怪的 mmap 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508112/

相关文章:

从 uint8_t 指针转换为 uint32_t 整数编译错误

PHP 脚本不断执行 mmap/munmap

C - 线程同步

c - 较高的波特率在 STM32F0Discovery 板上不起作用

linux - shm_open - 如何知道我是否打开了现有的共享内存

c - 复杂类型的 mmap 问题

c - 将文件映射到内存后出现段错误

c++ - 不太清楚为什么 mmap 没有按照我认为应该的方式进行。 C++ Linux

c - c 中的字符串与 fgets 进行比较

c - 为 Windows CE 移植 setsockopt() 和 RCVTIMEO