Linux--inter-process communication-semaphore
1. What is a semaphore?
It is a counter used to describe the number of certain resources, and realizes process communication by controlling other communication resources. It is responsible for data mutual exclusion, synchronization, etc. during this process. Mutual exclusion means that only one process of A and B is running during the same time period. Synchronize. That is, after process A is completed, process B is completed next, and there is a certain execution order.
2. Working principle
Two operating modes, P operation and V operation.
P operation (that is, apply for resources, and the semaphore is reduced by one)
V operation (release resources, and the semaphore is increased by one)
3. ipcs -s View semid
ipcrm -s id Delete id
4. Main functions
shmget Create semaphore
shmctl Delete
shmop P/V operation
Function prototype: int semop(int sem_id,struct sembuf *sops,size_t nsops);
sem_id is created through the shmget function
struct sembuf *sops parameter sops Points to an array of structures, each sembuf structure corresponds to a signal operation. The structure is as follows
struct sembuf { unsigned short sem_num;//sem_num是信号集中的索引,0代表第一个,1,代表第二个。。。 short sem_op; //操作类型,1 -->V操作,-1-->P操作 short sem_flg; //操作标志 };
sem_flg flag has two types: IPC_NOWAIT or SEM_UNDO. If the operation specifies SEM_UNDO (I gave it 0 below), it will automatically undo the process on termination.
nsops is the number of sops
~~ ~~~~~~~~~~~~~~********** Man function name can view the usage of the function**** ******~~~~~~~~~~~~~~~~~~~
5. Code implementation
comm.h
#pragma once #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #define _PATH_ "." #define _PROG_ID_ 0x6675 union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; int creatSem(int nsems); int get_Sem(); int initSem(int sem_id,int Which); int destroySem(int sem_id); int V_Sem(int sem_id,int which); int P_Sem(int sem_id,int which); static int op_Sem(int sem_id,int op,int which);
comm.c
#include"comm.h" int creatSem(int nsems) { key_t _key=ftok(_PATH_,_PROG_ID_); if(_key<0) { perror("ftok"); return -1; } umask(0); int sem_Flg=IPC_CREAT|IPC_EXCL|0666; int sem_id=semget(_key,nsems,sem_Flg); if(sem_id<0) { perror("semget"); return -1; } return sem_id; } int get_Sem() { key_t k=ftok(_PATH_,_PROG_ID_); return semget(k,0,0); } static int op_Sem(int sem_id,int op,int which) { struct sembuf sem; sem.sem_num=which; sem.sem_op=op; sem.sem_flg=0; return semop(sem_id,&sem,1); } int initSem(int sem_id,int Which) { union semun _semum; _semum.val=1; int ret= semctl(sem_id,Which,SETVAL,_semum); if(ret==-1) { perror("semctl"); return ret; } return ret; } int P_Sem(int sem_id,int which) { int ret=op_Sem(sem_id,-1,which); if(ret==-1) { perror("p_sem"); return -1; } return ret; } int V_Sem(int sem_id,int which) { int ret=op_Sem(sem_id,1,which); if(ret==-1) { perror("V_Sem"); return ret; } return ret; } int destroySem(int sem_id) { int ret=semctl(sem_id,0,IPC_RMID,NULL); if(ret==-1) { perror("semtrl"); return -1; } return ret; }
my_shm.c
#include"comm.h" int main() { int sem_id=creatSem(1); initSem(sem_id,0); pid_t id=fork(); if(id<0) { perror("for"); return -1; } else if(id==0) { int sem_id=get_Sem(); while(1) { P_Sem(sem_id,0); printf("A"); fflush(stdout); sleep(1); printf("A"); fflush(stdout); sleep(2); V_Sem(sem_id,0); } }else { while(1) { P_Sem(sem_id,0); printf("B"); fflush(stdout); sleep(1); printf("B"); fflush(stdout); sleep(1); V_Sem(sem_id,0); } waitpid(id,NULL,0); } }
Before using the semaphore (as shown below), you can see that the printing results are random.
After adding the semaphore (as shown below) (they all appear in pairs because they are mutually exclusive)
The above is the content of Linux--Inter-process Communication-Semaphore. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.
