- 论坛徽章:
- 0
|
发段以前封装过的
int nSemMalloc( key_t nSemKey, int* pnSemId )
{
// check parameter
if ( nSemKey <= 0 )
{
return ERR_PARAM_INVALID_VALUE;
}
if ( pnSemId == NULL )
{
return ERR_PARAM_POINTER_NULL;
}
bool bCreate = false;
int nSemId = -1;
int nRet = ERR_SUCCESS;
for ( int iOnce = 0; iOnce < 1; ++ iOnce )
{
nSemId = semget( nSemKey, 1, IPC_CREAT | IPC_EXCL | DC_DFT_IPC_MODE );
if ( (nSemId == -1) && (errno == EEXIST) ) // for restart
{
nSemId = semget( nSemKey, 1, IPC_EXCL | DC_DFT_IPC_MODE );
}
else if ( nSemId != -1 )
{
bCreate = true;
}
if ( nSemId == -1 )
{
int lErrno = errno;
switch ( lErrno )
{
case EACCES:
nRet = ERR_ACCESS_DENIED;
break;
case ENOENT:
nRet = ERR_OBJECT_NOT_EXIST;
break;
case ENOMEM:
nRet = ERR_MEMORY_INSUFFICIENT;
break;
case ENOSPC:
nRet = ERR_RES_INSUFFICIENT;
break;
default:
nRet = ERR_GENERAL;
break;
}
}
if ( bCreate )
{
union semun sem_arg;
memset( &sem_arg, 0, sizeof(sem_arg) );
sem_arg.val = 1;
if ( semctl(nSemId, 0, SETVAL, sem_arg) == -1 )
{
int lErrno = errno;
switch ( lErrno )
{
case EACCES:
case EPERM:
return ERR_ACCESS_DENIED;
break;
case EIDRM:
case EINVAL:
return ERR_PARAM_INVALID_VALUE;
break;
default:
return ERR_GENERAL;
break;
}
}
}
}
if ( nRet != ERR_SUCCESS )
{
if ( nSemId != -1 )
{
semctl( nSemId, 0, IPC_RMID );
}
return nRet;
}
*pnSemId = nSemId;
if ( bCreate )
{
return 0;
}
else
{
return 1;
}
}
int nSemFree( int* pnSemId )
{
// check parameter
if ( pnSemId == NULL )
{
return ERR_PARAM_POINTER_NULL;
}
if ( *pnSemId == -1 )
{
return ERR_PARAM_INVALID_VALUE;
}
if ( semctl(*pnSemId, 0, IPC_RMID) == -1 )
{
int lErrno = errno;
switch ( lErrno )
{
case EACCES:
case EPERM:
return ERR_ACCESS_DENIED;
break;
case EIDRM:
case EINVAL:
return ERR_PARAM_INVALID_VALUE;
break;
default:
return ERR_GENERAL;
break;
}
}
*pnSemId = -1;
return ERR_SUCCESS;
} |
|