简体   繁体   English

如何正确使用shm_open和mmap

[英]How to use shm_open with mmap properly

I am trying to create a shared memory area using examples and documentation I found online. 我正在尝试使用我在网上找到的示例和文档创建共享内存区域。 My goal is IPC , so I can make different processes talk to each other. 我的目标是IPC,所以我可以让不同的流程互相交流。

This my C file 这是我的C档案

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

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

struct stat sb;
off_t len;
char *p;
int fd;

fd = shm_open("test",  O_RDWR | O_CREAT); //,S_IRUSR | S_IWUSR);

if (fd == -1) {
    perror("open");
    return 1;
}

if (fstat(fd, &sb)==-1){
    perror("fstat");
    return 1;
}

/*if (!S_ISREG(sb.st_mode)){
    fprintf(stderr, "%s is not a file\n",fileName);
    return 1;
}*/

p = mmap(0, sb.st_size, PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED){
    perror("mmap");


    return 1;

}

if (close(fd)==-1) {
    perror("close");
    return 1;

}
for (len = 0; len < sb.st_size; len++) {
    putchar(p[len]);

}

if (munmap(p, sb.st_size) == -1) {
    perror("munmao");
    return 1;
}
fprintf(stderr,"\n");
return 0;
}

The problem is that I am getting a mmap: Invalid argument. 问题是我得到一个mmap:无效的参数。 I assume something is wrong with fd but have no clue how to fix it, any help would be appreciated. 我假设fd有问题,但不知道如何解决它,任何帮助将不胜感激。 I am on Yosemite using latest XCODE . 我在Yosemite使用最新的XCODE。

You need to extend the size of the shared memory mapping, at least the first time when you create it. 您需要扩展共享内存映射的大小,至少在您创建它时是第一次。 Right now its size is 0, and mmap is not going to allow you to make a zero length mapping. 现在它的大小是0,mmap不允许你进行零长度映射。

So instead of your fstat() call, do eg: 所以代替你的fstat()调用,例如:

size_t len = 4096;
if (ftruncate(fd, len) == -1) {
    perror("ftruncate");
    return 1;
}

And pass this len to mmap(). 并将此len传递给mmap()。

Your addr parameter is set to 0 , which might be reserved. 您的addr参数设置为0 ,可以保留。 Did you mean to use NULL ? 你的意思是使用NULL吗? This would be different than 0 . 这与0不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM