zoukankan      html  css  js  c++  java
  • 共享内存

    概念:共享内存是IPC机制的一种,雨荨两个不相关的进程访问同一段内存,也是传递数据一种非常有效的方式。

    共享内存---------写

    #include<sys/types.h>
    #include<sys/shm.h>
    #include<sys/ipc.h>
    #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>


    #define TEXT_SZ 2048

    struct shared_use_st
    {
    int written_by_you;
    char some_text[TEXT_SZ];


    }

    int main()
    {
    int running=1;
    int shmid;
    char buffer[TEXT_SZ];
    struct shared_use_st *shared_stuff;
    //1创建内存
    shmid = shmget((key_t)1234, sizeof(struct shared_use_st), IPC_CREAT)
    if(shmid==-1)
    {
    printf("creat shared memory failed");
    exit(EXIT_FAILURE);
    }


    //2映射内存
    shared_stuff= (struct shared_use_st*)shmat( shmid, NULL,0);

    //3循环
    while(running)
    {
    while(shared_stuff->written_by_you=1)
    (
    sleep(1);
    printf("wait read\n");
    )

    //3.1用户输入
    fgets(buffer,TEXT_SIZE,stdin);

    }
    //3.2将输入字符放入共享内存

    styncpy(shared_stuff->some_text,buffer,TEXT_SZ);
    shared_stuff->written_by_you=1;

    if(strncmp(buffer,"end",3)==0)
    running=0;

    //4脱离共享内存
    shmdt(( const void *)shared_stuff);
    return 1;

    }

    共享内存--------读

  • 相关阅读:
    linux中nc命令
    Centos6.5 安装zabbix3(收藏,非原创)
    紀念
    算法学习资源收集
    一道奇怪的求和题
    P5717 题解
    P1424 刷题记录
    P1888 题解
    P1422 刷题记录
    P1055 题解
  • 原文地址:https://www.cnblogs.com/1932238825qq/p/7366867.html
Copyright © 2011-2022 走看看