提问人:qicheng wang 提问时间:3/3/2023 更新时间:7/3/2023 访问量:79
如何集成semBCreate(VxWorks)和sem_init(Linux)信号功能
How to intergrate semBCreate(VxWorks) and sem_init(Linux) signal function
问:
我有一个任务,我有一个基于 Vxworks 的大代码,现在我想将其迁移到 Linux C 语言。我的目标是不更改我的原始代码,如下所示:
#ifdef COMPILE_IN_LINUX
pid = semBCreate(int arg1, long int arg2){
sem_init(&pid, int arg1, long int arg2);
}
#endif
我知道这是错误的,因为 Vxworks 的 semBCreate 只有 2 个参数,但 sem_init(Linux) 需要 3 个参数,上面的代码是用来表达我的目的的。我必须使用Vxworks的函数名来保留我的原始代码(semBCreate),但实现sem_init功能。 如何完成??????请帮帮我,谢谢!!!!
答:
0赞
Super Mario
7/3/2023
#1
我没有运行代码,但我会尝试如下操作:
typedef int SEM_ID;
typedef struct
{
// mapping the VxWorks semaphore ID with the Linux semaphore data
SEM_ID semId;
sem_t sem;
}semData;
#define MAX_NUMBER_OF_SEMAPHORES 100
semData semaphors[MAX_NUMBER_OF_SEMAPHORES]; // must be initialized with 0
SEM_ID semBCreate(int options, SEM_B_STATE initialState)
{
int i = 0;
for(; i < MAX_NUMBER_OF_SEMAPHORES; i++)
{
if(semaphors[i].semId == 0)
break; // free space for new semaphore found
}
if(i == MAX_NUMBER_OF_SEMAPHORES)
return 0; // no free space for new semaphore
// Since VxWorks semaphores only work within the same process, the second
// parameter can be set to 0.
// The value of the third parameter is the same as in VxWorks (0 or 1 for binary semaphore).
if(sem_init(&semaphors[i].sem, 0, (unsigned int)initialState) != 0)
return 0; // creating semaphore failed
semaphors[i].semId = i + 1;
return semaphors[i].semId; // creating semaphore successfull
}
STATUS semTake(SEM_ID semId, int timeout)
{
semData *semaphore = getSemaphore(semId);
if(semaphore == NULL)
return ERROR; // semaphore not found
// I assumed 1 tick to be 1ms. If not, more calculation is needed!
struct timespec tout;
tout.tv_sec = timeout / 1000;
tout.tv_nsec = (timeout % 1000) * 1000000;
if(sem_timedwait(&semaphore->sem, &tout) != 0)
return ERROR;
return OK;
}
STATUS semGive(SEM_ID semId)
{
semData *semaphore = getSemaphore(semId);
if(semaphore == NULL)
return ERROR; // semaphore not found
if(sem_post(&semaphore->sem) != 0)
return ERROR;
return OK;
}
static semData* getSemaphore(SEM_ID semId)
{
for(int i = 0; i < MAX_NUMBER_OF_SEMAPHORES; i++)
{
if(semaphors[i].semId == semId)
return &semaphors[i]; // semaphore found
}
return NULL; // semaphore not found
}
我希望这能让您了解它是如何工作的!
评论
int arg1
sem_init
sem_t*
pid_t*