有问题。 我有一个内容类似于 number:error_description 的文件。 现在我需要将此文件放入共享内存(POSIX)。如果修改任何内容,应将其保存到基本文件。 需要搜索共享内存中的内容(结果将通过消息队列发送到客户端)。 我如何实现这一切?首先,我认为我必须打开 (fopen("my_file", "r")) 然后我必须创建共享内存并映射文件。 有人可以帮助我吗?
编辑:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
/*
* \ /tmp/errors -> Error File
*/
#define MSGQ_HANDLER "/error_handler"
#define PATH_TO_FILE "/tmp/errors"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(void) {
int fd = open(PATH_TO_FILE, O_RDWR);
struct stat file_stat;
fstat(fd, &file_stat);
printf("File size: %zd\n", file_stat.st_size);
char *byte_ptr = mmap(NULL, file_stat.st_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if(byte_ptr == MAP_FAILED){
perror("error:");
}
while(1){
printf("%s\n", byte_ptr);
if(byte_ptr)
exit(1);
}
return EXIT_SUCCESS;
}
到目前为止,这就是我现在所拥有的。 读一行作品。 如何更改内容?
最佳答案
不要使用fopen
并忘记共享内存(我指的是sh*
API)。 mmap
就是所需要的。
使用open
和正确的选项(读/写)打开文件。然后使用 mmap
和选项 MAP_SHARED
。文件中的所有更改都将直接反射(reflect),并且对映射同一文件的所有进程可见。在 Linux 和 Solaris 上(在其他系统上我不知道,但 POSIX 或任何标准不保证)您甚至可以同时使用 read
/write
访问文件。但这是一个坏主意。
当然,来自不同进程的并发内存访问需要同步(互斥量、信号量等)。
关于c - Unix/C : put a file into shared memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164316/