Designing a Queue to be a shared memory

前端 未结 2 2073
情书的邮戳
情书的邮戳 2021-02-04 12:06

I\'m attempting to design/implement a (circular) queue (in C) as a shared memory so that it can be shared between multiple threads/processes.

The queue structure is as

相关标签:
2条回答
  • 2021-02-04 12:47

    When I messed with Unix IPC, I followed Beej's guide to Unix IPC. It even has some jokes! You can go directly to the shared memory section. It has snippets explaining each step, and a full example at the end.

    0 讨论(0)
  • 2021-02-04 12:49

    Here is a simple example that creates shared memory the size of a structure, writes some data to it and prints it out. Run one instance and it will create the shared memory and put some "data" in it, and then wait for a key press. Run a second instance in a different command prompt, and the second instance will print the contents of the memory.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题