zoukankan      html  css  js  c++  java
  • 共享主存实现进程间通信

    写程序

    1. #include"sys/ipc.h"  
    2. #include"sys/shm.h"  
    3. #include"sys/types.h"  
    4. #include"unistd.h"  
    5. #include"stdio.h"  
    6. #include"string.h"  
    7. typedef struct{  
    8.     char name[4];  
    9.     int age;  
    10. }people;  
    11.  
    12. main(int argc,char** argv)  
    13. {  
    14.     int shm_id,i;  
    15.     key_t key;  
    16.     char temp;  
    17.     people *p_map;  
    18.     char* name="..";  
    19.     key=ftok(name,0);  
    20.     if(key==-1)  
    21.         perror("ftok error!");  
    22.     shm_id=shmget(key,4096,IPC_CREAT|0666);  
    23.     if(shm_id==-1)  
    24.     {  
    25.         perror("shmget error!");  
    26.         return;  
    27.     }  
    28.     p_map=(people*)shmat(shm_id,NULL,0);  
    29.     temp='a';  
    30.     for(i=0;i<10;i++)  
    31.     {  
    32.         temp++;  
    33.         memcpy((*(p_map+i)).name,&temp,1);  
    34.         (*(p_map+i)).age=20+i;  
    35.     }  
    36.     if(shmdt(p_map)==-1)  
    37.         perror("detach error!");  
    38. }  

    读程序

    1. #include"sys/ipc.h"  
    2. #include"sys/shm.h"  
    3. #include"sys/types.h"  
    4. #include"unistd.h"  
    5. #include"stdio.h"  
    6. typedef struct{  
    7.     char name[4];  
    8.     int age;  
    9. }people;  
    10.  
    11. main(int argc,char** argv)  
    12. {  
    13.     int shm_id,i;  
    14.     key_t key;  
    15.     //char temp;  
    16.     people *p_map;  
    17.     char* name="..";  
    18.     key=ftok(name,0);  
    19.     if(key==-1)  
    20.         perror("ftok error!");  
    21.     shm_id=shmget(key,4096,IPC_CREAT|0666);  
    22.     if(shm_id==-1)  
    23.     {  
    24.         perror("shmget error!");  
    25.         return;  
    26.     }  
    27.     p_map=(people*)shmat(shm_id,NULL,0);  
    28.     //temp='a';  
    29.     for(i=0;i<10;i++)  
    30.     {  
    31.         printf("name:%s ",(*(p_map+i)).name);  
    32.         printf("age %d ",(*(p_map+i)).age);  
    33.     }  
    34.     if(shmdt(p_map)==-1)  
    35.         perror("detach error!");  
    36. }  

    本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/732489

  • 相关阅读:
    js事件循环机制event-loop
    javascript编译与执行
    css中rem,em,px的区别和使用场景
    float
    flex布局
    azoux's blog
    1004 成绩排名 PAT Basic Level
    1003 我要通过! PTA Basic Level
    腾讯云防盗链测试
    简单多项式求解
  • 原文地址:https://www.cnblogs.com/umgsai/p/3908219.html
Copyright © 2011-2022 走看看