Signal Volume classification
1. Two value semaphore: The value of the semaphore can be either 0 or 1.
2. Count Semaphore: The initial value of the semaphore is greater than 1.
What is a key value
1. Files are opened by file name to get the identifier of the file, and the semaphore is opened by the key value to get the semaphore identifier.
2. Specify the key value when creating the semaphore.
Specifying key values
1. Select any value
2. Through function constructs, for example: key_t ftok (char *fname, int id)
Key-Value Constructors
key_t Ftok (char *fname, int id)
The corresponding value in the kernel is taken out by the file name and then combined with the project ID to form a key value.
A.c
#include <sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<sys/ipc.h>#include<sys/sem.h>#include<unistd.h>voidMain () {//Open File intFD; FD= Open ("Board.txt", O_RDWR |o_append); //Create a key value intkey; Key= Ftok ("Board.txt",0); //Create Semaphore intSemid; Semid= Semget (Key,1, ipc_creat); //set the semaphoreSemctl (Semid,0, Setval,1);//set the value of semaphore 0 to 1//get the Semaphore structSembuf SOPs; Sops.sem_num=0; Sops.sem_op= -1; Semop (Semid,&sops,1); //Write DataWrite (FD,"Math",7); //Sleep WaitingSleepTen); //Write DataWrite (FD,"Is cancel", One); //release SemaphoreSops.sem_num =0; Sops.sem_op=1;
SOPs. SEM_FLG = Sem_undo ; Semop (Semid,&sops,1); //Close FileClose (FD);}
B.c
#include <stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<sys/ipc.h>#include<sys/sem.h>#include<unistd.h>voidMain () {//Open File intFD; FD= Open ("Board.txt", O_RDWR |o_append); //Create a key value intkey; Key= Ftok ("Board.txt",0); //Turn on Semaphore intSemid; Semid= Semget (Key,1, ipc_creat); //View semaphores intSemnum; Semnum= Semctl (Semid,0, getval);//View the value of the semaphore 0printf"Semaphore number is%d\n", Semnum); //get the Semaphore structSembuf SOPs; Sops.sem_num=0; Sops.sem_op= -1; SOPs. SEM_FLG = Sem_undo;
semop (Semid,&sops,1); //Write DataWrite (FD,"中文版 Exam", the); //release SemaphoreSops.sem_num =0; Sops.sem_op=1; Semop (Semid,&sops,1); //Close FileClose (FD);}
[State embedded Raiders][083][signal mutex programming]