Linux进程间通信之信号量

2014-11-24 11:04:08 · 作者: · 浏览: 1

在Linux编程中,要运用信号量实现互斥操作,用户空间需要调用几个系统调用,如下是一个用户空间例子。


#include


#include


#include


#include



#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\n");


semid=semget(SEMKEY,1,IPC_CREAT| PERMS);


if(semid<0)


{


printf("couldn't create semaphore\n");


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\n");


down();


printf("incritical code\n");


sleep(10);


up();


return0;


}


用户空间的程序中分为三步:


1, 调用semget系统调用创建信号量;


2, 调用semctl系统调用设置信号量初始值;


3, 调用semop系统调用实现同步互斥控制;



下面我们一步步看看内核中都是怎么实现的,内核中涉及到的关键数据结构与其主要的关系极其基本的操作如下图所示: