5

深入了解进程间通信:System V 信号量 + 共享内存

 3 years ago
source link: https://xie.infoq.cn/article/7afba59e0f6c8966c8e64d6ab
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言: 共享内存 指 (shared memory)在多处理器的计算机系统中,可以被不同中央处理器(CPU)访问的大容量内存。由于多个CPU需要快速访问存储器,这样就要对存储器进行缓存(Cache)。

3a6BNf7.png!mobile

writer:

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/shm.h>
#include<errno.h>
#defineSEM_KEY 4001
#defineSHM_KEY 5678
unionsemun {
intval;
};
intmain(void){
/*create a shm*/
intsemid,shmid;
shmid = shmget(SHM_KEY,sizeof(int),IPC_CREAT|0666);
if(shmid<0){
printf("create shm error\n");
return-1;
}
void* shmptr;
shmptr =shmat(shmid,NULL,0);
if(shmptr == (void*)-1){
printf("shmat error:%s\n",strerror(errno));
return-1;
}
int* data = (int*)shmptr;
semid = semget(SEM_KEY,2,0666);
structsembufsembuf1;
unionsemun semun1;
while(1){
sembuf1.sem_num=1;
sembuf1.sem_op=-1;
sembuf1.sem_flg=SEM_UNDO;
semop(semid,&sembuf1,1);
scanf("%d",data);
sembuf1.sem_num=0;
sembuf1.sem_op=1;
sembuf1.sem_flg=SEM_UNDO;
semop(semid,&sembuf1,1);
}
return0;
}

reader:

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/shm.h>
#include<errno.h>
#defineSEM_KEY 4001
#defineSHM_KEY 5678
unionsemun {
intval;
};
intmain(void){
/*create a shm*/
intsemid,shmid;
shmid = shmget(SHM_KEY,sizeof(int),IPC_CREAT|0666);
if(shmid<0){
printf("create shm error\n");
return-1;
}
void* shmptr;
shmptr =shmat(shmid,NULL,0);
if(shmptr == (void*)-1){
printf("shmat error:%s\n",strerror(errno));
return-1;
}
int* data = (int*)shmptr;
semid = semget(SEM_KEY,2,IPC_CREAT|0666);
unionsemun semun1;
semun1.val=0;
semctl(semid,0,SETVAL,semun1);
semun1.val=1;
semctl(semid,1,SETVAL,semun1);
structsembufsembuf1;
while(1){
sembuf1.sem_num=0;
sembuf1.sem_op=-1;
sembuf1.sem_flg=SEM_UNDO;
semop(semid,&sembuf1,1);
printf("the NUM:%d\n",*data);
sembuf1.sem_num=1;
sembuf1.sem_op=1;
sembuf1.sem_flg=SEM_UNDO;
semop(semid,&sembuf1,1);
}
return0;
}

相关视频:

【Linux内核】Linux内核进程间通信组件的实现(上): https://www.zhihu.com/zvideo/1288126445278330880

【Linux内核】Linux内核进程间通信组件的实现(下) : https://www.zhihu.com/zvideo/1288128472473387008


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK