我正在尝试在 linux 中编写 C 程序。这是代码: 在“shell>”提示符下输入我的输入后,gcc 给我以下错误:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
void main()
{
int shm_fd;
char read_buff[1024];
void *ptr = NULL;
shm_fd = shm_open("hello_class",O_RDONLY, 0666);
ptr = mmap(0,4096, PROT_READ, MAP_SHARED, shm_fd,0);
printf("%s", (char*)ptr);
shm_unlink("hello_class");
}
对于初学者,您需要在打开共享内存对象之前创建它。
通过 if/perror 添加一些基本的错误检查到原始代码:
shm_fd = shm_open("/hello_class",O_RDONLY, 0666);
if (shm_fd < 0) { perror("shm_open");exit(1);}
会产生错误:(来自perror函数)
shm_open: No such file or directory
创建共享内存区域;
shm_fd = shm_open("/hello_class",O_CREAT, 0666); // create shared memory
现在您将能够打开/读取它(通常是另一个进程)。即:
查看 svipc(7) 了解更多细节。特别是像信号量这样的同步机制。
但是,在这种情况下,正如鲍勃提到的那样,在向内存中写入有意义的内容之前,内存区域中不会有任何可用的东西。
注意:来自 shm_open(3) 联机帮助页,名称应以 /
开头