Linux-内存映射文件 [英] Linux - Memory Mapped File

查看:60
本文介绍了Linux-内存映射文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mmap实施凯撒密码.我认为密码工作得很好,但问题是mmap.它的想法是如果有更改,则更新文件.到目前为止,它不起作用.我可以读取并映射内存映射文件.但是,如果我进行任何修改,都会遇到分割错误.不幸的是,我自己无法解决问题.因此,如果您能帮助我,我将不胜感激.

I am trying to implement the caesar cipher with mmap. I think the cipher works so fine but the problem is, the mmap. The idea of it is to update the file, if there was a change. So far it isn't working. I can just read the memory mapped file and print it. But if I make any modificaiton, I get a segmentation fault. Unfortunately, I couldn't solve the problem myself. So, I would appreciate it, if you could help me with it.

这是代码.

int main (int argc, char *argv[]) {

    if(argc != 5)
       fprintf(stdeer, "usage: ./cipher (encrypt|decrypt) <file name> (casar| vigenere) <key>\n");

    // (encrypt / decrypt) can be found in argv[1]
    // filename in argv[2]
    // encryption method in argv[3]
    // key in argv[4]
    int fd = open(argv[2], O_RDWR, S_IWRITE | S_IREAD);
    if (fd < 0)
        hanle_error("open");

    off_t len = lseek(fd, 0, SEEK_END);
    if (len == (off_t)-1)
        handle_error("lseek");

    unsigned char* data = mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // Add PROT_WRITE
    if (data == MAP_FAILED)
        handle_error("mmap");

    char c = *argv[4];
    int key = 0;

    if(strcmp(argv[3], "caesar") == 0) {
        key = c - 48;
        if(strcmp(argv[1], "decrpyt") == 0)
            key = -key;
        int num = 0;
        for(int size_t i = 0; i < (size_t)len; i++) {
            if(data[i] >= 97 && data[i] <= 122) {
                num = data[i];
                num +=key;
                if(num > 'z') {
                    num -= 26;
                    data[i] = num + '0';
                } else if (num < 'a') {
                    num += 26;
                    data[i] = num + '0';
                } else {
                    data[i] = num + '0';
                }
            } else {
                continue;
            }
        }
    }

    return 0;
}

可能的输入可以是任何东西,例如

A possible input can be anything e.g.

SsWd asdas
qwmkfd aw.

上面的算法应该只修改小写字母,其余部分保持原样.

The algorithm above should just modify the lower case letters and leave the rest as it is.

我希望有人可以帮助我.

I hope someone might be able to help me.

此外,我只实现了凯撒密码.

Also, I only implemented the caesar cipher.

添加PROT_WRITE后,seg错误消失了.但是知道我对修改后的小写字母有奇怪的问号.有人知道为什么吗?

推荐答案

如果您也要写入文件,则

If you want to write to the file too, then

unsigned char* data = mmap(0, len, PROT_READ, MAP_SHARED, fd, 0);

应该是

unsigned char* data = mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

这可能不是唯一的问题,但可以解释段错误.

That may not be the only issue, but would explain the seg fault.

原因不言自明!

这篇关于Linux-内存映射文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆