The signal volume here is mainly used between different processes.
Requires four operations
- P operation
- V Operation
- The semaphore is initialized with the SEMCTL call command parameter setting Setval, which must be done before the semaphore is used.
- And you can delete the semaphore ID by semctl Call command set to Ipc_rmid:
Because the union Semun is not defined in the library, it needs to be defined by itself.
Three functions to use the semaphore
- Semget used to create a new semaphore or to obtain a key with an existing semaphore
- Semop used to change the semaphore value
- Semctl is used to directly control semaphore information, such as SEMOP must first use SEMCTL to give an initial value
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/sem.h>Unionsemun{intValstructSemid_ds *buf;unsigned Short int*Array;structSeminfo *__buf;};Static intSet_semvalue (void);Static voidDel_semvalue (void);Static intSemaphore_p (void);Static intSemaphore_v (void);Static intsem_id;Static intSet_semvalue (void){UnionSemun sem_union; Sem_union.val=1; Semctl (sem_id,0, setval,sem_union);}Static voidDel_semvalue (void){UnionSemun sem_union; Semctl (sem_id,0, ipc_rmid,sem_union);}Static intSemaphore_p (void){structSembuf Sem_b; sem_b.sem_num=0; sem_b.sem_op=-1; Sem_b.sem_flg=sem_undo;//auto ReleaseSemop (Sem_id,&sem_b,1);}Static intSemaphore_v (void){structSembuf Sem_b; sem_b.sem_num=0; sem_b.sem_op=1; Sem_b.sem_flg=sem_undo;//auto ReleaseSemop (Sem_id,&sem_b,1);}//main FunctionintMainintargcChar*agrv[]) {intIintPause_time;CharOp_char=' O '; Srand ((unsigned int) getpid ()); Sem_id=semget ((key_t)1234,1,0666| Ipc_creat);if(argc>1) {Set_semvalue (); Op_char=' X '; Sleep2); } for(i=0;i<Ten; i++) {semaphore_p ();printf("%c", Op_char); Fflush (stdout); Pause_time=rand ()%3; Sleep (Pause_time);printf("%c", Op_char); Fflush (stdout); Semaphore_v (); Pause_time=rand ()%2; Sleep (Pause_time); }printf("\n%d-finished\n", Getpid ());if(argc>1) {Sleep (Ten); Del_semvalue (); }Exit(0);}
[Email protected]:~/mytest./sem1 1 &
[1] 12839
[Email protected]:~/mytest ./sem1
Ooxxooxxooxxooxxooxxxxooxxooxxooxxooxxoo
12839-finished
12840-finished
[Email protected]:~/mytest$
The method of inter-process communication under Linux--signal volume