簡體   English   中英

從共享內存中讀取可變數量的結構

[英]Reading variable number of structs from shared memory

在C程序中,我創建了一個大容量的共享內存段,然后將可變數量的結構放入其中(本示例中為2)。

strcut message * x;
x = (struct message *)shmat(shmid,NULL,0);
x[0].a = 1;
x[0].b = 2;
x[1].a = 3;
x[1].b = 4;

有一個讀取器程序,必須讀取共享內存段中寫入的所有結構,但不知道其中有多少個結構。 我嘗試了以下方法:

struct message * x;
x = (struct message *)shmat(shmid,NULL,0);
 while(x!=NULL)
 {
printf("x.a = %d\n",x->a);
printf("x.b = %d\n",x->b);
printf("\n\n");
x=x++;
}

它正確地給了我2個結構,但是之后給了我0次(或隨機垃圾值)更多次(對於a和b),直到它用完共享內存段,然后給出了段錯誤。 我該怎么辦?

我正在使用UBUNTU。

您正在檢查while(x != NULL) -如果shmat()返回非NULL值,則永遠不會為NULL(除非您會因指針溢出而計數,但會提早獲得SEGV)。

如果要在內存中保留一堆結構,請也保存它們的數量並在用戶端重用。

即生產者:

char* ptr = shmat(shmid,NULL,0);

if(ptr != ((char*) -1)) {
    uint32_t* p_msg_count = (uint32_t*) ptr; 
    struct message* x = (struct message*) (ptr + sizeof(uint32_t));

    *p_msg_count = 2;  // <------

    // Fill in x
}

消費者:

char* ptr = shmat(shmid,NULL,0);
int xid, xcount;

if(ptr != ((char*) -1)) {
    uint32_t* p_msg_count = (uint32_t*) ptr; 
    struct message* x = (struct message*) (ptr + sizeof(uint32_t));

    xcount = (int) *p_msg_count; 
    for(xid = 0; xid < xcount; ++xid) {
        // Print x[xid] 
    }
}

PS x = x++; -這也非常糟糕(我認為即使編譯器也應該在這里抱怨)。 如果要獲取“ next” x,請單獨使用前綴增量: ++x

暫無
暫無

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

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