Linux interprocess communication, using shared memory mode

Source: Internet
Author: User

It's all right. For examples that want to learn to use shared memory communication between processes, the efficiency of shared memory is higher than that of Message Queuing and semaphores. Why is it?

(1) Shared memory is run in user space and is controlled by the application.

(2) Both the message queue and the semaphore are the user space that copies the data from one process user space to the kernel space and then the kernel control to another process.

#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>#defineKey 0x1234#defineSize 512#definePERM s_irusr| S_iwusrintMainvoid){    intShmid=shmget (key,size,ipc_creat|PERM); Char*shm=shmat (Shmid,null,0); if(shmid==-1) {perror ("Shmget"); return-1; }    if(Fork () >0){        intParent_id=Getpid (); fprintf (stdout,"----Parent pid=%d------\ n", parent_id); intstatus;  while(1){            Char*p_shm=shmat (Shmid,null,0); if(STRNCMP (P_SHM,"End",3)==0) {fprintf (stdout,"***recyle Child =%d*****\n", 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&AMP;&AMP;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; }}

Operation Result:

----Parent Pid=3477------Parent3477Send:hellochild3478recv:helloparent3477Send123456 Child3478Recv123456Parent3477Send Thisa testchild3478Recv Thisa testparent3477Send:endchild3478Recv:endRecyle Child =3478*****

Linux interprocess communication, using shared memory mode

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.