"Linux Advanced Programming" (Chapter 11th) System v interprocess communication 4

Source: Internet
Author: User
Tags semaphore strcmp

Shared memory

Shared memory is primarily used to enable large amounts of data transfer between processes.

Data structure definition for shared memory:

System limits on shared memory:

Shared memory vs. piping:

You can see the benefits of shared memory:

1. Shared memory only needs to be duplicated 2 times, and pipelines need 4 times

2. Shared memory does not need to switch between the kernel state and the user state, and the pipeline needs.

High efficiency in shared memory!

int Shmget (key_t __key, size_t __size, int __shmflg) : Create shared memory

First parameter: Value of key

Second parameter: size of the shared memory segment to create (bytes)

Third parameter: SHMFLG create identity, including Ipc_creat, Ipc_excl, ipc_nowait, Shm_r (readable), shm_w (writable)

int shmctl (int __shmid, int __cmd, struct shmid_ds *__buf) : Shared Memory control

First parameter: The shared memory identifier to be manipulated

Second parameter: action to be performed, Ipc_rmid, Ipc_set, Ipc_stat, Ipc_info, Superuser and Shm_lock (lock shared memory segment), Shm_unlock (unlock shared memory segment)

Third parameter: Temporarily shared memory variable information

void *shmat (int __shmid, __const void * __shmaddr, int __shmflg) : Mount shared memory to current process, return shared memory header address

First parameter: The shared memory identifier to be manipulated

Second parameter: Specify the shared memory mapped address, if it is 0, the system is selected.

Third parameter: Specify access permissions and mapping criteria for shared memory segments, 0 for readable writable

int shmdt (__const void *__shmaddr) : Separates shared memory from current process, parameter is shared memory mapped address

Test to write information in read-only shared memory:

#include <unistd.h>#include<stdlib.h>#include<stdio.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<errno.h>intMainintargcChar*argv[])    {key_t key; intshm_id; Char*ptr; Key= Ftok ("/",Ten); shm_id= Shmget (Key, -, ipc_creat| Shm_r);//Create SHMprintf"get the SHM ID is%d\n", shm_id);//Print ID    if(ptr = (Char*) Shmat (shm_id, NULL, shm_rdonly)) = = NULL)//mount in read-only mode    {        if(Shmctl (shm_id, Ipc_rmid, NULL) = =-1)//Delete if it failsPerror ("Failed to remove memory segment");    Exit (Exit_failure); }    //Print Mount Addressprintf"The attach add is%p\n", PTR); printf ("Now try to write the memory\n"); *ptr ='D'; printf ("*ptr =%c\n", *ptr);    SHMDT (PTR); Shmctl (shm_id, Ipc_rmid,0);}

A segment error occurred:

Conventions for shared memory between parent and child processes:

    • The child process of fork () inherits shared memory that is mounted by the parent process.
    • Calling exec to execute a new program, the shared memory is automatically uninstalled.
    • If exit () is called, the mounted shared memory is detached from the current process.

Here is an example of an application

To implement the communication of two unrelated processes, one is responsible for writing and the other is responsible for receiving. Use the signal to achieve synchronization, that is, when writing is not readable, read the time is not writable. Implemented with a unary semaphore, 0 means writable, 1 for readable

Note: In code implementations, it is actually a read-write rotation, which is written once and read once. does not achieve a true multi-process effect.

Code is validated and can be used

Send-side code:

#include <unistd.h>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<sys/sem.h>#include<errno.h>intMainintargcChar*argv[]) {    intrunning =1; intShid; intSemid; intvalue; void*sharem =NULL; structSembuf Sem_b; Sem_b.sem_num=0; SEM_B.SEM_FLG=Sem_undo; //Create Semaphore    if(Semid = Semget ((key_t)123456,1,0666| ipc_creat)) = =-1) {perror ("Semget");    Exit (Exit_failure); }    //initializes the semaphore to 0    if(Semctl (Semid,0, Setval,0) == -1) {printf ("SEM init error"); if(Semctl (Semid,0, Ipc_rmid,0) !=0) {perror ("Semctl");        Exit (Exit_failure);    } exit (Exit_failure); }    //Create shared MemoryShid = Shmget ((key_t)654321, (size_t)2048,0600| Ipc_creat);//Create shared Memory    if(Shid = =-1) {perror ("Shmget");    Exit (Exit_failure); }    //Mount shared memory to the current processSharem = Shmat (Shid, NULL,0); if(Sharem = =NULL) {Perror ("Shmat");    Exit (Exit_failure); }     while(running) {//test semaphore value, if 0 is writable        if(Value = Semctl (Semid,0, getval)) = =0) {printf ("Write Data operate\n"); printf ("Please input something:"); scanf ("%s", Sharem); Sem_b.sem_op=1; //performs semaphore plus 1 operation, allows read            if(Semop (Semid, &sem_b,1) == -1) {fprintf (stderr,"semaphore_p failed\n");            Exit (Exit_failure); }        }        //Compare whether it is an end symbol        if(strcmp (Sharem,"End") ==0) Running--;        } shmdt (Sharem); return 0;}

Receive-Side code:

#include <unistd.h>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<sys/sem.h>#include<errno.h>intMainintargcChar*argv[]) {    intrunning =1; intShid; intSemid; intvalue; void*sharem =NULL; structSembuf Sem_b; Sem_b.sem_num=0; SEM_B.SEM_FLG=Sem_undo; //Create Semaphore    if(Semid = Semget ((key_t)123456,1,0666| ipc_creat)) = =-1) {perror ("Semget");    Exit (Exit_failure); }    //Create shared MemoryShid = Shmget ((key_t)654321, (size_t)2048,0600| Ipc_creat);//Create shared Memory    if(Shid = =-1) {perror ("Shmget");    Exit (Exit_failure); }    //Mount shared memory to the current processSharem = Shmat (Shid, NULL,0); if(Sharem = =NULL) {Perror ("Shmat");    Exit (Exit_failure); }     while(running) {//test the semaphore value, if 1 is readable        if(Value = Semctl (Semid,0, getval)) = =1) {printf ("Read Data operate\n"); Sem_b.sem_op= -1; //performs a semaphore minus 1 operation, allowing write            if(Semop (Semid, &sem_b,1) == -1) {fprintf (stderr,"semaphore_p failed\n");            Exit (Exit_failure); } printf ("%s\n", Sharem); }        //Compare whether it is an end symbol        if(strcmp (Sharem,"End") ==0) Running--;    } shmdt (Sharem); //Delete Shared memory    if(Shmctl (Shid, Ipc_rmid,0) !=0) {perror ("Shmctl");    Exit (Exit_failure); }    //Delete Semaphore    if(Semctl (Semid,0, Ipc_rmid,0) !=0) {perror ("Semctl");    Exit (Exit_failure); }    return 0;}

"Linux Advanced Programming" (Chapter 11th) System v interprocess communication 4

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.