共享內存的使用c代碼

typedef struct st_setting
{
    char agen[10];
    unsigned char file_no;
}st_setting_t;

int main(int argc, char** argv)
{
#define IPCKEY 0x366378
    int         shm_id;
    st_setting_t  *p_setting1, *p_setting2;

    /*首先檢查共享內存是否存在,存在則先刪除*/
    shm_id = shmget(IPCKEY , 1028, 0640);
    if(shm_id != -1)
    {
        p_setting1 = (st_setting_t *)shmat(shm_id, NULL, 0);

        if (p_setting1 != (void *)-1)
        {
            shmdt(p_setting1);

            shmctl(shm_id,IPC_RMID,0) ;
        }
    }

    /*建立共享內存*/
    shm_id = shmget(IPCKEY, 1028, 0640 | IPC_CREAT | IPC_EXCL);
    if(shm_id == -1)
    {
        printf("shmget error\n");
        return -1;
    }

    /*將這塊共享內存區附加到本身的內存段*/
    p_setting1 = (st_setting_t *)shmat(shm_id, NULL, 0);

    strncpy(p_setting1->agen, "11111111", 10);
    printf("agen1 : %s\n", p_setting1->agen);

    p_setting1->file_no = 1;
    printf("file_no1 : %d\n",p_setting1->file_no);
    
    /*  此時可看到有進程關聯到共享內存的信息,nattch爲1*/
    system("ipcs -m");



    
    p_setting2 = (st_setting_t *)shmat(shm_id, NULL, 0);

    strncpy(p_setting2->agen, "2222", 10);
    printf("agen2 : %s\n", p_setting2->agen);

    p_setting2->file_no++;
    printf("file_no2 : %d\n",p_setting2->file_no);
    
    /*  此時可看到有進程關聯到共享內存的信息,nattch爲1*/
    system("ipcs -m");
    


    printf("agen1 : %s\n", p_setting1->agen);

    printf("file_no1 : %d\n",p_setting1->file_no);
    
    /*  此時可看到有進程關聯到共享內存的信息,nattch爲1*/
    system("ipcs -m");


    /*將這塊共享內存區從本身的內存段刪除出去*/
    if(shmdt(p_setting1) == -1)
       perror(" detach error ");

    if(shmdt(p_setting2) == -1)
       perror(" detach error ");

    /*此時可看到有進程關聯到共享內存的信息,nattch爲0*/
    system("ipcs -m");

    /*刪除共享內存*/
    if (shmctl( shm_id , IPC_RMID , NULL ) == -1)
    {
        perror(" delete error ");
    }
    
    /* 此時可看到有進程關聯到共享內存的信息,nattch爲0*/
    system("ipcs -m");


    return EXIT_SUCCESS;
}
相關文章
相關標籤/搜索