有問題。 我有一個內容如下的文件number:error_description。 現在我需要把這個文件共享內存(POSIX)。如果有任何內容被修改,它應該是保存到基本文件。 有必要搜索共享內存中的內容(結果將通過消息隊列發送給客戶端)。 如何實現所有這些?首先,我想我必須打開(fopen(「my_file」,「r」))然後我必須創建共享內存和mmap文件。 有人可以幫我嗎?Unix/C:將文件放入共享內存
編輯:
#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;
}
到目前爲止,這是我現在有。 閱讀一條線的作品。 如何更改內容?
似乎你還沒有嘗試過任何東西。試試看,在這裏問你是否需要特定的幫助。 – netcoder
定義「共享內存」並解釋你已經嘗試過的內容 – user1824407
@ user1824407:[共享內存](http://wikipedia.org/wiki/Shared_memory)(除非OP不知道他在說什麼)。 – netcoder