Skip to content

Instantly share code, notes, and snippets.

@jorben
Last active August 29, 2015 14:00
Show Gist options
  • Save jorben/11024922 to your computer and use it in GitHub Desktop.
Save jorben/11024922 to your computer and use it in GitHub Desktop.
信号量实现的互斥锁,示例中有且只有一个进程能获得锁,并设置SEM_UNDO在进程异常时自动释放锁,避免因为进程异常而死锁。
// 创建/打开 只允许一个进程进行P操作的信号量,并等待它
static bool s_wait_sem()
{
const key_t SEM_KEY = 0xA001FFFF;
int semid = semget(SEM_KEY, 1, IPC_CREAT|IPC_EXCL|0666);
if (semid >= 0)
{
// 计算机重启后,首次启动进程
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
arg.val = 1; // 只允许一个进程P操作
int n = semctl(semid, 0, SETVAL, arg);
if (n != 0)
{
// UPDATER_LOG("semctl-SETVAL failed[%d]", errno);
semctl(semid, 0, IPC_RMID);
return false;
}
}
else
{
// 可能已经存在,尝试打开
semid = semget(SEM_KEY, 1, IPC_CREAT|0666);
if (semid < 0)
{
UPDATER_LOG("semget-IPC_CREAT failed[%d]", errno);
return false;
}
}
struct sembuf lock_it;
lock_it.sem_num = 0;
lock_it.sem_op = -1;
lock_it.sem_flg = SEM_UNDO; // 进程退出(正常或非正常)时可以自动释放锁
int n = semop(semid, &lock_it, 1); // 只有一个进程能够获得锁,其他进程会卡在这里等待
if (n != 0)
{
// 出错?!
// UPDATER_LOG("semop-lock failed[%d]", errno);
semctl(semid, 0, IPC_RMID);
return false;
}
return true;
}
@jorben
Copy link
Author

jorben commented Apr 20, 2014

函数声明为static,只是限制仅在当前文件中可调用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment