2012-02-13 122 views
4

我需要在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個鏈接。

回答

4

您應該測試mmap的結果。如果它給出MAP_FAILED查看errno找出原因。

你會更好的mmap頁的整數倍,每個經常4K字節,並給予通過sysconf(_SC_PAGESIZE)

您可以使用stat找出的大小(約許多其他數字)的一些指定的文件。

你可以在現有的Linux程序上使用strace來了解他們在做什麼系統調用。

又見this/proc/

+1

謝謝你的幫助,我發現我寫的文件寫保護,因爲這一切都失敗了。 – RobbingDaHood 2012-02-14 13:58:54

1

scanf()調用應該是sscanf(),和第二敞開應該使用"mapTester"代替argv[1]作爲文件名。當我修復這些錯誤時,您的發佈程序就會運行(打印出22並在文件中保留44)。

+0

我無法讓代碼與您所說的更改一起工作。我不知道如何在評論中格式化代碼,所以我只是把它放在消息的末尾。我使用g ++編譯器命令,也許你正在使用另一個? – RobbingDaHood 2012-02-14 13:39:36

+0

好吧我不能添加更多的代碼,因爲它太長了。我複製了我在這裏寫的代碼,並更改了2個地方,並在代碼的最後部分出現了分段錯誤。但謝謝你的好消息,非常有幫助:) – RobbingDaHood 2012-02-14 13:41:02

相關問題