• linux进程间通信,使用共享内存方式


    闲来没事给想要学习进程间使用共享内存通信的例子,共享内存的效率比消息队列、信号量都要高?为什么呢?

      (1)共享内存是运行在用户空间的,由应用程序控制。

      (2)消息队列和信号量都是把数据从一个进程用户空间复制到内核空间,然后再由内核控件复制到另外一个进程的用户空间。

    #include <unistd.h>
    #include <stdio.h>
    #include <string.h>
    #include <sys/mman.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #define key 0x1234
    #define size 512
    #define PERM S_IRUSR|S_IWUSR
    int main(void)
    {
        int shmid=shmget(key,size,IPC_CREAT|PERM);
        char *shm=shmat(shmid,NULL,0);
        if(shmid==-1){
            perror("shmget");
            return -1;
        }
        if(fork()>0){
            int parent_id=getpid();
            fprintf(stdout,"----parent pid=%d------
    ",parent_id);
            int status;
            while(1){
                char *p_shm=shmat(shmid,NULL,0);
                if(strncmp(p_shm,"end",3)==0){
                    fprintf(stdout,"***recyle child =%d*****
    ",wait(&status));
                    break;
                }
                else {
                    memset(p_shm,'',size);
                }
                printf("parent %d send:",parent_id);
                fgets(p_shm,size,stdin);
                sleep(1);
            }
        }
        else
        {
            while(1){
                char *c_shm=shmat(shmid,NULL,0);
                if(strlen(shm)>0){
                    printf("child %d recv:%s",getpid(),c_shm);
                }
                if(strlen(shm)>0&&strncmp(shm,"end",3)==0){
                    memcpy(shm,"end",3);
                    break;
                }
                sleep(1);
            }
        }
        if(shmdt(shm)==-1){
            perror("shmdt");
            return -1;
        }
        if(shmctl(shmid,IPC_RMID,NULL)==-1){
            perror("shmctl");
            return -1;
        }
    }

    运行结果:

    ----parent pid=3477------
    parent 3477 send:hello
    child 3478 recv:hello
    parent 3477 send:123456
    child 3478 recv:123456
    parent 3477 send:this a test
    child 3478 recv:this a test
    parent 3477 send:end
    child 3478 recv:end
    ***recyle child =3478*****
  • 相关阅读:
    SCU 3133(博弈)
    SCU 3132(博弈)
    hdu 5183(hash)
    hdu3329(2次dfs)
    hdu5179(数位dp)
    zoj2314(有上下界的网络流)
    CF 519E(树上倍增求lca)
    hdu1251(Trie树)
    SCU 2009(数位dp)
    【Leetcode】Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/innobase/p/5077138.html
Copyright © 2020-2023  润新知