c - 文件的内存映射是否存在

标签 c

如果该文件还没有一个文件,我必须对其进行内存映射。我提供的代码不起作用。我从另一个文件调用此函数两次,每次它都创建不同的 mmapPtr。

char *mmapPtr;

void MemoryMapFile()
{

    int fd;
    struct stat sbuf;
    if(mmapPtr==NULL) <--- why is this executed when I called MemoryMapFile() second time
    {
        // get file descriptor of file
        if ((fd = open("example.c", O_RDONLY)) == -1) 
        {
            perror("open");
            exit(1);
        }
        if (stat("example.c", &sbuf) == -1) 
        {
            perror("stat");
            exit(1);
    }
        if ((data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) ==  (caddr_t)(-1)) 
        {
            perror("mmap");
            exit(1);
        }
        printf("mmap pointer %p \n",mmapPtr);
    }

最佳答案

如果 char* mmapPtr 不是全局或静态指针,则该行

if(mmapPtr==NULL) 

永远不会返回 true,因为未初始化的指针具有随机值,而不是 NULL 值。



如果你声明

char *mmapPtr = NULL;

它应该可以工作,(忽略可能的其他错误)

关于c - 文件的内存映射是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14881741/

相关文章:

为 Linux 创建一个窗口管理器

c - "produce_numbers"中的 pthread_cond_wait 给我段错误

c - c程序的段错误

c - 如何停止输入换行符

c - 在 FreeBSD/bin/and/usr/bin 中返回 vs 退出

objective-c - 为什么 fget 不工作?

c - 错误: can't find a register in class ‘GENERAL_REGS’ while reloading ‘asm’

c++ - SDL 正在发送错误的 Controller 索引

c - 如何将给定级别的二叉搜索树转换为链接链?

c - 尝试检索值时,将指针传递给函数会导致段错误