Linux 进程通信-共享储存

头文件

#include<sys/types.h>  
#include <sys/shm.h> 
void shm_test(){
    key_t key(ftok(".", 3));
    pid_t pid;

    if((pid = fork()) > 0){
        int shmid = shmget(key, 100, IPC_CREAT | IPC_EXCL | 0600);    //Create
        auto buf = (char *)shmat(shmid, nullptr, 0);        //Link

        print("shmid:", shmid);

        while(read(STDIN_FILENO, buf, 100)){
            if(buf[0] == 'q') break;
        }
        print("shmdt:", shmdt(buf));    //Separate
        wait(0);
        shmctl(shmid, IPC_RMID, 0);    //Delete
    }else if(pid == 0){
        sleep(1);
        int shmid = shmget(key, 0, 0);
        auto buf = (char *)shmat(shmid, nullptr, 0);
        char tmp[10] = {0};

        while(1){
            sleep(2);
            if(buf[0] != 0) {
                if (buf[0] == 'q') break;
                else{
                    print(buf);
                    memset(buf, 0, 100);
                }
            }
        }

        print("son shmdt:", shmdt(buf));
    }
}

APUE:“共享储存段紧靠在栈之下”


更多:进程间通信(四)—共享内存


猜你喜欢

转载自blog.csdn.net/m_n_n/article/details/79841977