Linux --處理序間通訊--共用記憶體

來源:互聯網
上載者:User
一、共用記憶體
共用記憶體是最高效的通訊方式,因為不需要一個進程先拷貝到核心,另一個進程在存核心中讀取。

二、 ipcs -m 查看共用記憶體
ipcrm -m 刪除共用記憶體

三、主要函數
shmget 建立

shmctl 刪除

shmat 掛接

shmdt 取消掛接

********* man 函數名 查看*****
四、代碼實現
comm.h

1 #pragma once    2 #include<stdio.h>    3 #include<stdlib.h>    4 #include<unistd.h>    5 #include<sys/ipc.h>    6 #include<sys/shm.h>    7 #define _PATH_ "."    8 #define _PROJID_ 0x666    9 #define _SHM_SIZE_ 4096   10 int getShmget();   11 int destoryShm(int shm_id);   12 char* at_shm(int shm_id);   13 int delete_Shm(char *addr);

comm.c

1 #include"comm.h"    2 int getShmget()    3 {    4     key_t key=ftok(_PATH_,_PROJID_);    5     6     int shmflg=IPC_CREAT |0666;    7     int shm_id=shmget(key,_SHM_SIZE_,shmflg);    8     if(shm_id<0)    9     {   10         perror("shmget");   11         return -1;   12     }      13     return shm_id;   14 }      15    16 int destoryShm(int shm_id)   17 {   18     return shmctl(shm_id,IPC_RMID,NULL);   19 }      20    21 char* at_shm(int shm_id)   22 {   23     return (char*)shmat(shm_id,NULL,0);   24 }   25 int delete_Shm(char *addr)   26 {   27     return shmdt(addr);   28 }

client.c

1 #include"comm.h"    2 int main()    3 {    4     int shm_id=getShmget();    5     char *addr=at_shm(shm_id);    6     int i=0;    7     for(;i<_SHM_SIZE_;i++)    8     {    9         addr[i ]='A';   10         addr[i+1]='\0';   11         sleep(1);   12     }      13     delete_Shm(addr);   14     return 0;   15 }

server.c

1 #include"comm.h"    2 int main()    3 {    4     int shm_id=getShmget();    5     char * addr=at_shm(shm_id);    6     int i=0;    7     for(;i<_SHM_SIZE_;i++)    8     {    9         printf("%s\n",addr);   10         sleep(1);   11     }   12     delete_Shm(addr);   13     destoryShm(shm_id);   14     return 0;   15 }

運行結果

以上就是Linux --處理序間通訊--共用記憶體的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.