This is a code snippet from a c code utilizing semaphores:
sem_t match, more_needed;
if (sem_trywait(&match) == 0)
{
sleep(0.5);
sem_post(&more_needed); // release more needed
}
// other code
sem_wait(&match);
Now i want to integrate a custom system call which does all semaphore operations in kernel space. Please verify whether i’m using the correct syntax and in kernel code to replicate the functionality of above mentioned code.
do notice down_trylock and down_interruptible in the following snippet
code in kernel space(for custom system call 333):
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/semaphore.h>
static struct semaphore match_sem;
static struct semaphore more_needed_sem;
static int semaphores_initialized = 0;
asmlinkage long custom_semaphore_operation(int operation)
{
if (!semaphores_initialized) {
sema_init(&match_sem, 0);
sema_init(&more_needed_sem, 1);
semaphores_initialized = 1;
}
switch (operation)
{
case 1: // sem_trywait (&match)
printk("match tryn");
return down_trylock(&match_sem);
case 2: // sem_post (&more_needed);
printk("no more neededn");
up(&more_needed_sem);
break;
case 3: // sem_wait (&match);
printk("match requestedn");
if (down_interruptible(&match_sem) != 0)
return -EINTR; // Semaphore wait interrupted by a signal
break;
}
}
// corresponding code in userspace
if (syscall(333, 1) == 0) /* acquire match*/
{
sleep(0.5);
syscall(333, 2); /* release more needed*/
}
// other code
syscall(333, 3);
New contributor
Yusra Asim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.