以下代码段是在nvram读写时用的lock和unlock函数及实现,只要在get和set nvram之前和之后加上_nvram_lock()
和_nvram_unlock(),就能实现当前进程读写nvram时不被其他进程打断。
参考的博文:
http://blog.csdn.net/xiajun07061225/article/details/8475738
参考文件:
Linux信号量学习.pdf
-
#include <sys/ipc.h>
-
#include <sys/sem.h>//包含信号量定义的头文件
-
#define NVRAM_SEM_KEY 0XAEEAEE
-
-
//联合类型semun定义
-
union semun{
-
int val;
-
struct semid_ds *buf;
-
unsigned short *array;
-
};
-
static int sem_id;//信号量ID
-
-
-
//函数:设置信号量的值
-
static int set_semvalue(void)
-
{
-
union semun sem_union;
-
sem_union.val = 1;
-
-
if(semctl(sem_id,0,SETVAL,sem_union))
-
return 0;
-
-
return 1;
-
}
-
-
//函数:删除信号量
-
static void del_semvalue(void)
-
{
-
union semun sem_union;
-
-
if(semctl(sem_id,0,IPC_RMID,sem_union))
-
printf("NVRAMERRO:Failed to delete semaphore\n");
-
}
-
-
//函数:信号量P操作:对信号量进行减一操作
-
static int semaphore_p(void)
-
{
-
struct sembuf sem_b;
-
-
sem_b.sem_num = 0;//信号量编号
-
sem_b.sem_op = -1;//P操作
-
sem_b.sem_flg = SEM_UNDO;
-
-
if(semop(sem_id,&sem_b,1) == -1)
-
{
-
printf("NVRAMERRO:semaphore_p failed\n");
-
return 0;
-
}
-
-
return 1;
-
}
-
-
//函数:信号量V操作:对信号量进行加一操作
-
static int semaphore_v(void)
-
{
-
struct sembuf sem_b;
-
-
sem_b.sem_num = 0;//信号量编号
-
sem_b.sem_op = 1;//V操作
-
sem_b.sem_flg = SEM_UNDO;
-
-
if(semop(sem_id,&sem_b,1) == -1)
-
{
-
printf("NVRAMERRO:semaphore_v failed\n");
-
return 0;
-
}
-
-
return 1;
-
-
}
-
-
-
static int _lock()
-
{
-
//取得一个已有信号量的键
-
sem_id = semget((key_t)NVRAM_SEM_KEY,0,0666 );
-
if((sem_id<0)&&(errno==ENOENT))
-
{
-
printf("NVRAM:MUST creat semaphore\n");
-
//创建一个新的信号量或者是取得一个已有信号量的键
-
sem_id = semget((key_t)NVRAM_SEM_KEY,1,0666 | IPC_CREAT);
-
if(sem_id < 0)
-
{
-
printf("NVRAMERRO:failed to creat semaphore\n");
-
return 0;
-
}
-
if(!set_semvalue())
-
{
-
printf("NVRAMERRO:failed to initialize semaphore\n");
-
return 0;
-
}
-
}
-
else if(sem_id<0)
-
{
-
printf("NVRAMERRO:failed to get semaphore\n");
-
return 0;
-
}
-
if(!semaphore_p())
-
{
-
printf("NVRAMERRO:failed to lock\n");
-
return 0;
-
}
-
-
return 1;
-
}
-
-
static int _unlock()
-
{
-
if(!semaphore_v())
-
{
-
printf("NVRAMERRO:failed to unlock\n");
-
return 0;
-
}
-
return 1;
-
}
-
-
-
static int _nvram_lock()
-
{
-
int i=0;
-
-
while (i++ < MAX_LOCK_WAIT) {
-
if(_lock())
-
return 1;
-
else
-
usleep(500000);
-
}
-
return 0;
-
}
-
/*nvram file unlock*/
-
static int _nvram_unlock()
-
{
-
int i=0;
-
-
while (i++ < MAX_LOCK_WAIT) {
-
if(_unlock())
-
return 1;
-
else
-
usleep(500000);
-
}
-
return 0;
-
}
阅读(1680) | 评论(0) | 转发(0) |