簡體   English   中英

在open()和mmap()之后無法訪問數據結構-總線錯誤

[英]Unable to access data structure after `open()` and `mmap()` - Bus Error

我正在寫一個基於fork()的服務器,我需要在父進程與其分叉的子進程之間共享一個數組。 特別要求我為實現使用文件和mmap() ,以便以后可以輕松使用fcntl()鎖。

由於某些原因,當我嘗試執行以下代碼時,我在struct_array[i].number = -1;行上遇到了Bus Error struct_array[i].number = -1;

if ((fd = open("/tmp/tmp-file", O_RDWR | O_CREAT | O_TRUNC, 777)) == -1) {
    perror("open");
}

struct my_struct *struct_array = mmap(NULL, struct_size, PROT_READ | PROT_WRITE,
    MAP_SHARED, fd, 0);

if (struct_array == MAP_FAILED) {
    perror("mmap");
}

for (i = 0; i < CLIENTS_SIZE; i++) {
    struct_array[i].number = -1;
}

我一次又一次地瀏覽了手冊頁,但是肯定有一些我想念的東西。

如果相應的偏移量超出文件末尾,則訪問映射的內存范圍內的地址將產生總線錯誤。

在這種情況下,文件大小為零,則應使文件至少長struct_size個字節(使用ftruncate)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM