Inter-process communication (3)-semaphores and processes communication semaphores

Source: Internet
Author: User

Inter-process communication (3)-semaphores and processes communication semaphores

I will use several blogs to summarize several methods of communication between processes in Linux. I will write the summary at the beginning in each blog of this series.

Communication between processes

  • MPs queue
  • Message Queue
  • Signal
  • Semaphores
  • Shared storage Zone
  • Socket)

Inter-process communication (II)-Message Queue Portal: http://www.cnblogs.com/lenomirei/p/5642575.html

Inter-process communication (I)-pipe Portal: http://www.cnblogs.com/lenomirei/p/5636339.html

Article 3 is coming! The first two articles have a lot of access traffic. Thank you very much.

Write down the related operation functions and methods of semaphores this time. As before, the test code will be posted at the end of the blog!

If I have studied the operating system, I should be familiar with the semaphore term. At the same time, the signal and the semaphore are different!

Semaphores are mostly used for synchronization and mutex between processes. To put it simply, it means synchronization and mutex.

Synchronization: Processing competition is synchronization, and scheduling of process execution is synchronization. Each process has a certain sequence of execution.

Mutex: mutual access to critical resources that cannot be shared, and two new control problems (mutual exclusion can be said to be a special synchronization)

Competition: When concurrent processes compete to use the same resource, we are called a competition process.


To put it simply, the semaphoreWorking mechanism(Because it is really simple), yesDirectly understood as a counter(Of course, it cannot be so simple when locking, not just semaphores .)There will be an initial value (> 0), WheneverIf a process requests to use semaphores, perform the-1 operation on semaphores through a P operation.When countingWhen the device is reduced to 0, there will be no resources, and other processes must wait for access (for example, busy waiting or sleep), WhenAfter the process completes this step (we call it a critical section), it will execute the V operation to perform the + 1 operation on the semaphore.

Critical section: not a simple area! Is the lock Range code!

Critical resource: can only be used by one process at the same time (cannot be shared by multiple processes). mutex is required.

We can say that semaphores are also a way of inter-process communication. For example, a simple implementation of mutex lock is a semaphores. A process uses mutex lock and notifies (Communication) other processes that want the mutex lock, block their access and use (I am using it! @_@!)

In fact, the operation functions of semaphores are similar to those of the previous ones.

  • Semaphore Creation

You will be familiar with it! Similar to message queue

  • Function prototype: int semget (key_t key, int nsems, int semflg );
  • Header file: # include <sys/types. h> # include <sys/ipc. h> # include <sys/sem. h>
  • Parameter Parsing
    • Key_t is not explained in detail. I have talked about it in the message queue article.
    • The nsems parameter indicatesCreate several semaphoresTo be precise, the semget FunctionCreate a semaphore set(The one that contains a lot of semaphores can be simply understoodSemaphore Array), That is, to create a semaphore set with several semaphores, you can choose to create only one
    • The semflg is still the same. If we use two parameters, IPC_CREAT and IPC_EXCL, I will talk about it in the message queue, so there will be no extra fees.

The following shows a disadvantage of semaphores.

  • Semaphore Initialization

This indicates that the initialization and creation of semaphores are separated. Why is this because no parameter of the semaphores size is provided during the creation, semaphores can be set to a large value (not just 1). Of course, if set to 1, mutual access is achieved. For example, typical producer and consumer problems, however, if the reader semaphores in Reader writers are different (because multiple readers can read them at the same time), this model is not explained here.

The disadvantage is that, after initialization and creation are separated, thread security issues will occur. process A has just created A semaphore and has not yet been initialized. process B has started to operate on the semaphore PROCESS P (brother! I have not set a value for initialization !) The-1 operation cannot be performed at all, and it will be blocked. I don't know what is going on (try this error in person )...

No more nonsense. The function is still a routine.

  • Function prototype: int semctl (int semid, int semnum, int cmd ,...);
  • Header file: # include <sys/types. h> # include <sys/ipc. h> # include <sys/sem. h>
  • Parameter Parsing
    • The first semid is used to identify semaphores. The returned value when semget is successful is
    • Semnum is very useful. I just mentioned that I applied for a semaphore set,This parameter indicates the number of semaphores to be initialized by the function. This parameter starts from 0 and 0 indicates the first semaphores.
    • Cmd uses this SETVAL to set the variable this time.

After SETVAL is set, the fourth parameter in the Variable Parameter List can be used. Here, a magic consortium is passed in (I found it in the manual, but it cannot be used, or write one by yourself)

1 union semun {2                int              val;    /* Value for SETVAL */3                struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */4                unsigned short  *array;  /* Array for GETALL, SETALL */5                struct seminfo  *__buf;  /* Buffer for IPC_INFO6                                            (Linux-specific) */7            };

It is it! It is it! Let's take a look at the first one. I don't know much about other things ),Val is the initial value.The parameter is a variable (no pointer is required)

This function will be deleted later. ctl is the abbreviation of control. Many operations have it.

  • Semaphore operation

At the beginning, I wrote two methods of operation, namely P operation and V operation, which are implemented through a function. This function is also associated with a struct.

  • Function prototype: int semop (int semid, struct sembuf * sops, unsigned nsops );
  • Header file: # include <sys/types. h> # include <sys/ipc. h> # include <sys/sem. h>
  • Parameter Parsing
    • Old friend of the first semid
    • The second is the struct.
    • Third RepresentationYou want to operate on several semaphores at the same time(Why doesn't it mean index of semaphores? We can say it together in the struct), because semaphores may have many semaphores, and each operation is unrealistic. This parameter provides a simultaneous operation.
1 struct sembuf2 {3     unsigned short sem_num;  /* semaphore number */4     short          sem_op;   /* semaphore operation */5     short          sem_flg;  /* operation flags */6 };

 

Sem_num is the index of semaphore. The subscript of the semaphore you want to operate. sem_op is a short integer. Here, 1 or-1 indicates the V and P Operations respectively, the last semflg manual mentioned two

IPC_NOWAIT: Generally, IPC_NOWAIT is generally used by IPC. If you don't have to wait, you have to sleep)

SEM_UNDO) it is not allowed to be hung up (even worse !!! This is very important (additional space is required! @ _ @), Because it may fail to wake up once it is suspended or sleep! (Pending may wait for the event) This is not good, it will make other waiting processes hungry, especially when it fails, it will be even worse, it is impossible to execute the V operation, the waiting process will wait infinitely, and it is not good to apply for semaphores recursively, especially when mutex semaphores cause deadlocks. At this time, UNDO will cancel all the previously done things, P operation will be executed, and the semaphore will change from 0 back to 1, all of you are happy.

  • Semaphore Deletion

Semctl again, similar to message queue Deletion

  • Function prototype: I just wrote ~!
  • Header file: I just wrote ~!
  • Parameter Parsing: I just wrote ~!
  • The difference is that you only need to replace SETVAL with IPC_RMID (of course, the variable parameter list will not be followed. Let's take a look at the test example)

 

 

Now, the basic operations have been completed,Show me the code

My program is divided into three files: comm. h (Public header file) comm. c (encapsulate basic functions) server. c (use fork to complete the use of semaphores between parent and child processes)

Basic functions: Simulate thread security (simple version). The parent process prints "A" A "and the child process prints" B "" B ", the execution sequence may cause cross-printing, but I don't want this. I want to connect AA and BB separately! Complete this function

First read the previous version

Cross-print is not what I want

Function complete continuous printing

Comm. h

 

 1 #include <stdio.h> 2 #include <sys/ipc.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <sys//sem.h> 6 #include <stdlib.h> 7 #include <errno.h> 8  9 10 #define _PATH_NAME_ "/tmp"11 #define _PROJ_ID_ 0x666612 13 static int comm_create_sem(int flags,int num);14 int create_sem(int num);15 int get_sem();16 void P_sem(int sem_id,int index);17 void V_sem(int sem_id,int index);

 

 

 

Comm. c

 

 1 #include "comm.h" 2  3 union semun { 4                int              val;    /* Value for SETVAL */ 5                struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */ 6                unsigned short  *array;  /* Array for GETALL, SETALL */ 7                struct seminfo  *__buf;  /* Buffer for IPC_INFO 8                                            (Linux-specific) */ 9            };10 11 12 static int comm_create_sem(int flags,int num)13 {14   key_t _key=ftok(_PATH_NAME_,_PROJ_ID_);15   if(_key<0)16   {17     printf("%d:%s",errno,strerror(errno));18   }19   int sem_id;20   if((sem_id=semget(_key,num,flags))<0)21   {22     printf("semget errno,%d:%s",errno,strerror(errno));23   }24   return sem_id;25 }26 27 int create_sem(int num)28 {29   int flags=IPC_CREAT | IPC_EXCL;30   int sem_id=comm_create_sem(flags,num);31   union semun v;32   v.val=1;33   if(semctl(sem_id,0,SETVAL,v)<0)//init34   {35     printf("init error,%d:%s",errno,strerror(errno));36   }37   return sem_id;38 }39 40 int get_sem()41 {42   int flags=0;43   return comm_create_sem(flags,0);44 }45 46 47 void P_sem(int sem_id,int index)48 {49   struct sembuf s;50   s.sem_num=index;51   s.sem_op=-1;52   s.sem_flg=0;53   if(semop(sem_id,&s,1)<0)54   {55     printf("op errro,%d:%s",errno,strerror(errno));56   }57 }58 59 void V_sem(int sem_id,int index)60 {61   struct sembuf s;62   s.sem_num=index;63   s.sem_op=1;64   s.sem_flg=0;65   if(semop(sem_id,&s,1)<0)66   {67     printf("op error,%d:%s",errno,strerror(errno));68   }69 70 }71 72 void destory_sem(int sem_id)73 {74   semctl(sem_id,0,IPC_RMID);75 }

 

 

Server. c

 

 1 #include "comm.h" 2  3  4  5 int main() 6 { 7   int pid; 8   pid=fork(); 9   if(pid>0)10   {11     //father12     int sem_id=create_sem(1);13     while(1)14     {15       P_sem(sem_id,0);16       printf("A");17       fflush(stdout);18       sleep(1);19       printf("A");20       fflush(stdout);21       V_sem(sem_id,0);22     }23   }24   else25   {26     //child27     while(1)28     {29       int sem_id=get_sem();30       P_sem(sem_id,0);31       printf("B");32       fflush(stdout);33       sleep(1);34       printf("B");35       fflush(stdout);36       V_sem(sem_id,0);37     }38   }39 40   return 0;41 }

 

Related Article

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.