I am writing a Linux char driver, and I want to release a semaphore when the driver closes. The thing is, I won’t be sure whether or not the user has grabbed the semaphore yet. What is the appropriate way to do this?
/* Not my code, but demonstrates the problem I face */
if (userland_var)
down(&my_sem);
/* ... */
/* Okay, now I want to release this semaphore, if held,
but I don't know the value of userland_var */
/* OPTION 1: */
up(&my_sem);
/* OPTION 2: */
my_sem = sema_init(&my_sem, 1);
/* OPTION 3: */
down_trylock(&my_sem);
up(&my_sem);
What’s the “right” way to force the thing open?
I don’t think it’s what you want to hear, but don’t “force” a semaphore open. This will only introduce new problems (probably extremely subtle and difficult to find ones).
If you had a guard on the semaphore acquisition, you should use that same guard over the signal. Yes, this may introduce previously-not-considered design changes, but it’s the Right Thing to do.
For your specific problem, saving a copy of
userland_varas your module-semaphore-usage’s state might be one way to approach it.