San*_*raj 10 c memory posix shared-memory
我正在尝试将(循环)队列(在C中)设计/实现为共享内存,以便它可以在多个线程/进程之间共享.
队列结构如下:
typedef struct _q {
int q_size;
int q_front;
int q_rear;
int *q_data;
}queue;
Run Code Online (Sandbox Code Playgroud)
它支持以下功能:
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);
Run Code Online (Sandbox Code Playgroud)
根据用户提到的队列大小,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;
}
Run Code Online (Sandbox Code Playgroud)