[Country EMBED strategy] [085] [Shared memory communication]

Source: Internet
Author: User

Shared memory

Shared memory is one of the IPC mechanisms that allows two related processes to access the same memory, which is an efficient way to pass data.

A.c

#include <sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<stdio.h>#include<string.h>#defineSIZE 2048typedefstructsharemem{intFlag//Share Flag    CharData[size];//Sharing Data}sharemem;voidMain () {//Create shared Memory    intkey; intShmid; Key= Ftok ("./",0); Shmid= Shmget (Key,sizeof(SHAREMEM), ipc_creat); //Mapping Shared MemorySharemem *Sharemem; Sharemem= (Sharemem *) Shmat (Shmid, NULL,0); //set up shared memorySharemem->flag =0;  while(1){        //Judging shared flags         while(Sharemem->flag! =0); //Get user Input        CharBuffer[size];                Fgets (buffer, SIZE, stdin); //Write shared Memorystrncpy (sharemem->data, buffer, SIZE); Sharemem->flag =1; //determine whether to exit        if(STRNCMP (Buffer,"quit",4) ==0){             Break; }    }        //out of shared memorySHMDT ((Const void*) sharemem);}

B.c

#include <sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<stdio.h>#include<string.h>#defineSIZE 2048typedefstructsharemem{intFlag//Share Flag    CharData[size];//Sharing Data}sharemem;voidMain () {//Open Shared Memory    intkey; intShmid; Key= Ftok ("./",0); Shmid= Shmget (Key,sizeof(SHAREMEM), ipc_creat); //Mapping Shared MemorySharemem *Sharemem; Sharemem= (Sharemem *) Shmat (Shmid, NULL,0); //set up shared memorySharemem->flag =1;  while(1){        //Judging shared flags         while(Sharemem->flag! =1); //Read Shared memory        CharBuffer[size]; strncpy (buffer, Sharemem-data, SIZE); Sharemem->flag =0; //Show shared Memoryprintf"%s", buffer); //determine whether to exit        if(STRNCMP (Buffer,"quit",4) ==0){             Break; }    }        //out of shared memorySHMDT ((Const void*) sharemem); //Delete Shared memoryShmctl (Shmid, Ipc_rmid, NULL);}

[Country EMBED strategy] [085] [Shared memory communication]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.