我需要在Linux中使用mmap()進行一些流入和輸出類。爲此,我嘗試製作一些測試代碼,將一些整數寫入文件,保存它,再次加載並將文件中的數據寫入到文件中。如果這個測試代碼有效,那麼它不會成爲一個問題。如何在Linux系統上使用mmap()進行讀取和寫入
當我第一次開始時,我得到了段錯誤,如果我沒有發現任何事情發生,所以我GOOGLE了一下。我發現這本書http://www.advancedlinuxprogramming.com/alp-folder/alp-ch05-ipc.pdf其中第107頁左右有一些有用的代碼。我複製粘貼代碼,並做了一些小的變化,並得到這個代碼:
int fd;
void* file_memory;
/* Prepare a file large enough to hold an unsigned integer. */
fd = open ("mapTester", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
//Make the file big enough
lseek (fd, 4 * 10 + 1, SEEK_SET);
write (fd, "", 1);
lseek (fd, 0, SEEK_SET);
/* Create the memory mapping. */
file_memory = mmap (0, 4 * 10, PROT_WRITE, MAP_SHARED, fd, 0);
close (fd);
/* Write a random integer to memory-mapped area. */
sprintf((char*) file_memory, "%d\n", 22);
/* Release the memory (unnecessary because the program exits). */
munmap (file_memory, 4 * 10);
cout << "Mark" << endl;
//Start the part where I read from the file
int integer;
/* Open the file. */
fd = open (argv[1], O_RDWR, S_IRUSR | S_IWUSR);
/* Create the memory mapping. */
file_memory = mmap (0, 4 * 10, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
close (fd);
/* Read the integer, print it out, and double it. */
scanf ((char *) file_memory, "%d", &integer);
printf ("value: %d\n", integer);
sprintf ((char*) file_memory, "%d\n", 2 * integer);
/* Release the memory (unnecessary because the program exits). */
munmap (file_memory, 4 * 10);
但我的「標誌」 COUT後得到了段富爾茨。
然後我代替這個「閱讀部分」:
fd = open("mapTester", O_RDONLY);
int* buffer = (int*) malloc (4*10);
read(fd, buffer, 4 * 10);
for(int i = 0; i < 1; i++)
{
cout << buffer[i] << endl;
}
那就是讓我發現,該文件是空的一些工作的代碼。我嘗試了幾種寫入映射的方式,而不會改變結果。
那麼我怎樣才能讓我的代碼寫入? 我的mmap閱讀代碼看起來好嗎(以防萬一你可以看到一些明顯的缺陷)?
我發現了一些其他資源,但沒有幫助我,但因爲我是一個新用戶,我可能只發布最多2個鏈接。
謝謝你的幫助,我發現我寫的文件寫保護,因爲這一切都失敗了。 – RobbingDaHood 2012-02-14 13:58:54