Both POSIX and system v are protocols applied to the system, and POSIX IPC and system v IPC can be used for inter-process communication
1. The difference in functions: System V function names do not have underscores, POSIX function names have underscores
2. The way to operate the semaphore:
POSIX IPC: Use sem_wait() to subtract 1 from the semaphore, and sem_post() to increase the semaphore by 1
system V: Use a semget () Get semaphore identifier, for sembuf provided, a semop () using the signal
3. POSIX unnamed semaphore can put data into shared memory for inter-process communication
4. System v semaphore has id
System V semaphore and Posix semaphore
system v adds 1 code to the semaphore
/*对信号量加一*/
void sem_v(int semid)
{
struct sembuf sops = {0,1,0};//默认阻塞
int ret = semop(semid,&sops, 1);
if (ret == -1)
{
perror("");
}
}
system p implements the reduction of 1 code for the semaphore
//对信号量减1
void sem_p(int semid)
{
struct sembuf sops = { 0,-1,0 };//默认阻塞
int ret = semop(semid, &sops, 1);
if (ret == -1)
{
perror("");
}
}
The following external operations on the semaphore minus 1 (to obtain the semaphore identifier externally, call the custom sem_p(), sem_v() functions to operate on the signal set)
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <iostream>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int main()
{
int semid = semget(1234, 0, 0);// get a System V semaphore set identifier
if (semid == -1)
{
semid = semget(1234, 1, IPC_CREAT | 0666);//打开失败创建
}
sem_p(semid2);
return 0;
}