首页 / 操作系统 / Linux / Linux进程间通信之信号量
Linux进程间通信包括管道、消息队列、System V等等,其中System V包括三种:信号量、消息队列、共享内存,这里只简单介绍信号量机制。在Linux编程中,要运用信号量实现互斥操作,用户空间需要调用几个系统调用,如下是一个用户空间例子。#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h> #define SEMKEY 1234L#define PERMS 0666 struct sembuf op_down[1]={0,-1,0};struct sembuf op_up[1]={0,1,0}; int semid=-1;int res; void init_sem(){ semid=semget(SEMKEY,0,IPC_CREAT |PERMS); if(semid<0) { printf("create semaphore
"); semid=semget(SEMKEY,1,IPC_CREAT| PERMS); if(semid<0) { printf("couldn"t create semaphore
"); exit(-1); } res=semctl(semid,0,SETVAL,1); }} void down(){ res=semop(semid,&op_down[0],1);} void up(){ res=semop(semid,&op_up[0],1);} int main(){ init_sem(); printf("beforecritical code
"); down(); printf("incritical code
"); sleep(10); up(); return0;}用户空间的程序中分为三步:1, 调用semget系统调用创建信号量;2, 调用semctl系统调用设置信号量初始值;3, 调用semop系统调用实现同步互斥控制; 下面我们一步步看看内核中都是怎么实现的,内核中涉及到的关键数据结构与其主要的关系极其基本的操作如下图所示: