一江春水向東流

          做一個有思想的人,期待與每一位熱愛思考的人交流,您的關(guān)注是對我最大的支持。

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            44 隨筆 :: 139 文章 :: 81 評論 :: 0 Trackbacks

          IPC之共享存儲區(qū)
          用共享存儲區(qū)進(jìn)行進(jìn)程間通信主要有以下步驟組成
          1. Create shared memory?
          int shmget(key_t key, int size, int shmflg);?
          if ((shm_id = shmget (mykey, sizeof (struct sharedbuf), 0600 | IFLAGS)) < 0)
          ??? perror ("shmget");

          2. Attach shared memory?
          char *buf = shmat (shm_id, 0, 0);
          ?
          3. Read / Write shared memory?
          sharedbuf->size = size_;?
          memcpy(sharedbuf->buf, mybuf, size_);?
          memcpy(mybuf, sharedbuf->buf, sharedbuf->size);?
          ?
          3. Detach shared memory (optional)?
          shmdt (buf);
          ?
          4. Remove shared memory?
          if (shmctl (shm_id, IPC_RMID, (struct shmid_ds *)0) < 0)?
          ??? perror ("shmctl");

          一個測試過的實(shí)例
          #include <stdio.h>
          #include <sys/types.h>
          #include <sys/shm.h>
          #include <sys/ipc.h>
          #define SHM_MODE (SHM_R | SHM_W)
          #define SHM_SIZE 2048

          int main()
          {
          ?int segment_id, segment_size;
          ?char *shared_memory;
          ?pid_t pid;
          ?
          ?if((segment_id = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)/*獲得共享內(nèi)存標(biāo)識符*/
          ??perror("shmget error!\n");
          ?if((shared_memory = shmat(segment_id, 0, 0)) == (void *)-1)/*進(jìn)程和共享內(nèi)存段相連接*/
          ??perror("shmat error!\n");
          ?printf("test1 send a message to share memory.\n");
          ?sprintf(shared_memory, "Hello test2\n");
          ?shmdt(shared_memory);/*脫離鏈接*/
          ?pid = fork();
          ?if(pid < 0)
          ??perror("Creating process error!\n");
          ?else if(pid > 0)
          ?{
          ??wait(NULL); /*父進(jìn)程等待子進(jìn)程結(jié)束*/
          ??shmctl(segment_id, IPC_RMID, 0);/*子進(jìn)程結(jié)束,父進(jìn)程將共享內(nèi)存刪除*/
          ??exit(0);
          ?}
          ?else
          ?{???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
          ??if((shared_memory = shmat(segment_id, 0, 0)) == (void*)-1)/*子進(jìn)程和共享內(nèi)存連接*/
          ???perror("shmat error!\n");
          ??printf("test2 get a message form share memory:%s",shared_memory);
          ??shmdt(shared_memory);
          ?}
          }?????

          相關(guān)參考:http://blog.csdn.net/Apollo_zhc/archive/2006/06/01/768694.aspx

          posted on 2007-05-04 17:27 allic 閱讀(495) 評論(0)  編輯  收藏 所屬分類: linux/UNIX 應(yīng)用開發(fā)
          主站蜘蛛池模板: 贵溪市| 报价| 延寿县| 苏尼特左旗| 淮北市| 改则县| 沙湾县| 那曲县| 万载县| 穆棱市| 锡林浩特市| 樟树市| 保德县| 乌苏市| 垦利县| 凤山县| 紫云| 麻栗坡县| 富裕县| 绥宁县| 绥德县| 镶黄旗| 鄂州市| 潜江市| 衡东县| 阿坝县| 普定县| 林周县| 三穗县| 施甸县| 隆昌县| 措勤县| 丹寨县| 华蓥市| 淮滨县| 开原市| 申扎县| 应城市| 南宫市| 从江县| 栖霞市|