[英]Designing a Queue to be a shared memory
我正在嘗試將(循環)隊列(在 C 中)設計/實現為共享內存,以便它可以在多個線程/進程之間共享。
隊列結構如下:
typedef struct _q {
int q_size;
int q_front;
int q_rear;
int *q_data;
}queue;
其中支持以下功能:
int empty_q(queue *q);
int display_q(queue *q);
int create_q(queue **q, int size);
int delete_q(queue **q);
int enqueue(queue *q, int data);
int dequeue(queue *q, int *data);
根據用戶提到的隊列大小,q_data 的內存將在 create_q() 中分配。
問題:如何使用“sys/shm.h”中提供的系統函數為該隊列創建共享內存? 任何使用 shmget()、shmat()、shmctl() 等為隊列數據結構創建/附加/檢索/刪除共享內存的代碼片段/示例都會有很大幫助。
這是一個簡單的示例,它創建結構大小的共享內存,向其中寫入一些數據並將其打印出來。 運行一個實例,它將創建共享內存並將一些“數據”放入其中,然后等待按鍵。 在不同的命令提示符下運行第二個實例,第二個實例將打印內存的內容。
typedef struct
{
char a[24];
int i;
int j;
} somestruct;
void fillshm(int shmid) {
somestruct *p;
if ( (p = shmat (shmid, NULL, 0)) < 0 )
{
perror("shmat");
exit(1);
}
printf("writing to shared memory\n");
strcpy(p->a, "my shared memory");
p->i = 123;
p->j = 456;
}
void printshm(int shmid)
{
somestruct *p;
if ( (p = shmat (shmid, NULL, 0)) < 0 )
{
perror("shmat");
exit(1);
}
printf( "%s, %d, %d\n", p->a, p->i, p->j );
}
int main( int argc, char *argv[] ) {
int shmid;
// see if the memory exists and print it if so
if ( (shmid = shmget (1234, 0, 0)) >= 0 )
printshm( shmid );
else
{
// didn't exist, so create it
if ( (shmid = shmget (1234, sizeof( somestruct ), IPC_CREAT | 0600)) < 0 )
{
perror("shmget");
exit(1);
}
printf( "shmid = %d\n", shmid );
fillshm(shmid);
printf( "Run another instance of this app to read the memory... (press a key): " );
getchar();
// delete it
if ( shmctl (shmid, IPC_RMID, NULL) < 0 )
{
perror("semctl");
exit(1);
}
}
return 0;
}
當我搞砸 Unix IPC 時,我遵循了 Beej 的 Unix IPC 指南。 它甚至有一些笑話! 您可以直接進入共享內存部分。 它有解釋每個步驟的片段,最后有一個完整的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.