Implementation of inter-process communication and synchronization

Source: Internet
Author: User
Tags message queue mutex semaphore stub

Process Communication
    • Memory sharing
      A process Create shared area shmget (...) map memory share Shmat (...)
      The B process finds the shared area by key to map the memory share
      Inter-process communication
      Revoke the respective memory mappings SHMDT ()
      Delete a shared area shctl ()

    • Piping pipe
      A process communicates with the B process to create two pipelines
      When A->b, the write end in a is required to read end in B, and the pipe is blocked when the write is full, and the pipe is blocked when there is nothing to read;

The following code is implemented on Xcode because some class libraries are not supported under vs * * *////MAIN.C//Pipesample////Created by Lean on 15/8/2.//Copyright (c) 2015 WB. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>//Provide wait function #include <unistd.h>//delivery process #include <string.h>intMainintargcConst Char* argv[]) {intpipe_fd[2];//The read end and write end of the pipelinepid_t Child_pid;CharPipe_buf;//Initialize    memset(PIPE_FD,0,sizeof(int)*2);//Open the read-write port through the pipe, because the pipeline is unidirectional, so two pipes are required    if(Pipe (PIPE_FD) ==-1)return-1;//fork a child processChild_pid=fork ();if(child_pid==-1)return-1;if(child_pid==0) {//Close Write endClose (pipe_fd[1]); while(Read (pipe_fd[0], &pipe_buf,1) >0) {Write (Stdout_fileno, &pipe_buf,1); } Close (pipe_fd[0]); }Else{Close (pipe_fd[0]); Write (pipe_fd[1],"H",1); Write (pipe_fd[1],"K",1); Close (pipe_fd[1]);    Wait (NULL); }return 0;}


    • Unix Domain sockets (UDS)

Server-side monitoring of IPC requests
Client initiates IPC request
Establishing an IPC connection
Client sends data to the server

The following code is a non-running code for the sample code **********////SVR_FOR_UDS.C//Pipesample////Created by Lean on 15/8/2.//Copyright (c) 2015 WB. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <string.h>#include <sys/socket.h>#include <sys/un.h>#include <sys/types.h>#define Uds_path "Uds_test"#define Buff_sizeintUds_client () {intsocket_client=-1;intdata_len=0; size_t addr_size=0;structSockaddr_un addr_srv;Charstr[ -];memset(STR,0,sizeof(Char)* -);strcpy(STR,"This was the test for UDS");if(Socket_client=socket (Af_unix, Sock_stream,0)) <0) {return-1; } Addr_srv.sun_family=af_unix;strcpy(Addr_srv.sun_path,uds_path); Addr_size=offsetof (structSockaddr_un, Sun_path) +strlen(Addr_srv.sun_path);if(Connect (Socket_client,Const structSOCKADDR *) &addr_srv, addr_size) <0) {return-1; }if(Send (Socket_client, str,strlen(str),0) <0) {Close (socket_client);return-1; }if(DATA_LEN=RECV (socket_client, str, -,0)) >0) {str[data_len]=' + ';printf("echo from server:%s", str);return 0; }Else{Close (socket_client);return-1; }}intUds_server () {intsocket_srv=-1;intsocket_client=-1;structSockaddr_un addr_srv,addr_client;CharStr[buff_size];memset(STR,0,sizeof(Char) *buff_size);if(Socket_srv=socket (Af_unix,sock_stream,0)) <0) {return-1; } Addr_srv.sun_family=af_unix;strcpy(Addr_srv.sun_path, Uds_path);if(Bind (Socket_srv, (structSOCKADDR *) &addr_srv, Offsetof (structSockaddr_un,sun_path) +strlen(Addr_srv.sun_path)) <0) {return-1; }if(Listen (Socket_srv,5) <0) {return-1; } while(1) {size_t nrecv; size_t sz=sizeof(addr_client);if(Socket_client=accept (Socket_srv, (structSOCKADDR *) &socket_client, &sz)) ==-1) {return-1; }if(NRECV=RECV (socket_client, str, -,0)) <0) {Close (socket_client); Break; }if(Send (Socket_client, str, NRECV,0) <0) {Close (socket_client); Break;    } close (socket_client); }return 0;}
  • Rremote Procedure Calls (RPC)
    Client process Call Stub interface
    Stubs are packaged according to operating system requirements and are transmitted by the kernel to the Server Core
    Server-side stub to decompress and invoke package matching process
    The service-side process executes the operation.
    The server passes the results to the client in the above process.

    Synchronization mechanism
  • Signal Volume semaphore
    Semaphore S (semaphore) indicates the available number of shared resources, initialized to 1
    Operation P also expressed as wait ()
    When the process wants to enter the shared area to perform p operations, reduce the s count, and if the count is >=0, you can manipulate the shared resource,
    Otherwise, join the wait queue until a process frees the shared resource and then pulls a resource out of the wait queue.
    Operation V is also expressed as signal ()
    When the process wants to exit the share to perform a V operation to increase the s count, the semaphore plus one, if the semaphore >0 at this time,
    Indicates that the waiting for the resource is not accessed and is returned directly. Otherwise the V operation is to wake the related objects in the wait queue.
    Example:
    Suppose you have a lot of collaborative processes that are reading or writing a record in a data file. You may want to strictly coordinate access to this file, so you use the initial value of 1 for the semaphore,
    Two operations are performed on this semaphore, the first Test and the value of the semaphore is reduced by 1, then the value of the semaphore is tested and added 1. When the first process accesses a file, it cuts the value of the semaphore by 1,
    And succeeds, the semaphore value now becomes 0, and the process can continue to execute and access the data file. However, if another process wants to access this file,
    It also reduced the value of the semaphore by 1, and the result was that the file could not be accessed because the semaphore value changed to-1. This process will be suspended until the first process completes access to the data file.
    When the first process completes the access to the data file, it increases the semaphore value to make it 1 again, and now the waiting process is woken up, and its minus 1 operation on the semaphore will be successful.

  • Mutex Mutex
    The default operation for semaphores is counting Semaphore, whereas for a semaphore with an access value of 0/1 becomes a binary Semaphore,
    Two states that represent whether a resource is occupied
  • Enhancement monitor
    Enhancement is an extension and improvement of the semaphore mechanism, and is a more portable synchronization method.
    Enhancement are objects and modules that can be accessed by multiple processes, threads, and protected by a mutex, meaning that only one visitor can access them at the same time.
    The language of implementing the pipe-path mechanism is delphi,java,python,ruby,c# and so on.
    Features: security mutex sharing.
Android synchronization mechanism specific implementation
    • Mutext is a re-encapsulation based on the Pthread interface.
      Android4.4.2 Source/system/core/include/utils/mutex.h
      Lock () Gets the resource lock if the resource available function returns immediately if the resource is unavailable then it becomes blocked
      Unlock () frees the resource lock if there is a waiting process to wake the waiting process
      Trylock () Gets the resource lock gets and returns 0 if the resource is available, and returns no 0 if the resource is not available.
inline Mutex::~Mutex() {    pthread_mutex_destroy(&mMutex);}inline status_t Mutex::lock() {    return -pthread_mutex_lock(&mMutex);}inline void Mutex::unlock() {    pthread_mutex_unlock(&mMutex);}inline status_t Mutex::tryLock() {    return -pthread_mutex_trylock(&mMutex);}

The Autolock constructor acquires a binary semaphore and locks it, and the destructor unlocks its mutex

class   Autolock  {public:inline autolock   (mutex  & mutex ) : MLock  (mutex )  {Mlock.lock () ;} Inline autolock   (mutex  * mutex ) : Mlock (* mutex )  {Mlock.lock () ;} Inline ~autolock   ()  {Mlock.unlock () ; } Private: mutex  & MLock; };
    • Condition
      Android4.4.2 source/system/core/include/utils/condition.h dependent on mutex completion
      Because a process needs to meet certain conditions in order to execute a line of code, if the polling method is more efficient. Condition is designed to solve this particular kind of demand problem.
      Wait () waits for a condition to be met, as to what the condition is, the system ignores it, equivalent to the "black box" design.
Enum Wakeuptype {Wake_up_one= 0, Wake_up_all= 1};//Wait on the condition variable. Lock the mutex before calling.        //Release lock sleep Add lock    inlinestatus_t Condition:: Wait(Mutex&Mutex) {return -pthread_cond_wait(&Mcond,&Mutex.Mmutex); }//Same with relative timeoutstatus_t waitrelative (Mutex&Mutex, nsecs_t reltime);//Signal The condition variable, allowing one thread to continue.    voidSignal ();//Signal The condition variable, allowing all threads to continue.    voidBroadcast (); enum {PRIVATE = 0, SHARED= 1};
    • Barrier e:/android4.4.2 Source Code/frameworks/native/services/surfaceflinger/barrier.h
      A model based on mutext and condition. That is, "Barrier" is the condition that fills the condition.
      Barrier is specially designed for Surfaceflinger.
      Mutex::autolock _l (lock), maintaining the atomic nature of the operation.
 Public: inlineBarrier() : State(CLOSED) {} inline ~barrier () {}voidOpen () {Mutex::autolock _l (Lock);        state = opened;    Cv.broadcast (); }voidClose () {Mutex::autolock _l (Lock);    state = CLOSED; }voidWait ()Const{Mutex::autolock _l (Lock); while(state = = CLOSED) {//Release lock enters sleep and then acquires lockCv.wait (Lock); }    }Private:enum{opened, CLOSED}; Mutable MutexLock; mutable Condition CV;volatile    intState;};

Reference documents:
Semaphore (semaphore), message queue, and shared memory (Share) for inter-process communication between Linux
Http://www.cnblogs.com/biyeymyhjob/archive/2012/11/04/2753535.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Implementation of inter-process communication and synchronization

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.