c - protect sem_wait() from signals using pthread_sigmask() -
i have library accesses hardware resource (spi) via 3rd party library. library, , in turn spi resource, accessed multiple processes need lock resource semaphores, lock functions below:
static int spi_lock(void) { struct timespec ts; if (clock_gettime(clock_realtime, &ts) == -1) { syslog(log_err,"failed read clock: %s\n", spisem, strerror(errno)); return 3; } ts.tv_sec += 5; if (sem_timedwait(bcoms->spisem, &ts) == -1) { syslog(log_err,"timed out trying acquire %s: %s\n", spisem, strerror(errno)); return 1; } return 0; } static int spi_unlock(void) { int ret = 1; if (sem_post(bcoms->spisem)) { syslog(log_err,"failed release %s: %s\n", spisem, strerror(errno)); goto done; } ret = 0; done: return ret; }
now problem library used in daemon , daemon stopped via kill signal. kill signal while holding semaphore lock , hence servers cannot restarted because lock perpetually taken. fix trying block signals shown below (i waiting hardware test on atm):
static int spi_lock(void) { sigset_t nset; struct timespec ts; sigfillset(&nset); sigprocmask(sig_block, &nset, null); if (clock_gettime(clock_realtime, &ts) == -1) { syslog(log_err,"failed read clock: %s\n", spisem, strerror(errno)); return 3; } ts.tv_sec += 5; // 5 seconds acquire semaphore heaps, better bloody !!! if (sem_timedwait(bcoms->spisem, &ts) == -1) { syslog(log_err,"timed out trying acquire %s: %s\n", spisem, strerror(errno)); return 1; } return 0; } static int spi_unlock(void) { sigset_t nset; int ret = 1; if (sem_post(bcoms->spisem)) { syslog(log_err,"failed release %s: %s\n", spisem, strerror(errno)); goto done; } sigfillset(&nset); sigprocmask(sig_unblock, &nset, null); ret = 0; done: return ret; }
but having read man pages sigprocmask() says in multi-threaded system use pthread_sigmask(), , 1 of servers want protect multi threaded. don't understand if use pthread_sigmask() in library, , main parent thread spawns spi read thread uses locking functions in library, read thread protected, can't main thread still receive kill signal , take down daemon while holding mutex signals disabled on read thread getting me no where? if there better solution locking problem?
thanks.
i don't think approach work. can not block sigkill or sigstop. unless saying daemon getting different signal (like sighup). think it's bad practice block signals library call. can result in adverse effects on calling application. example, application may relying on particular signals , missing such signals cause function incorrectly.
as turns out there isn't easy way solve problem using semaphores. alternative approach use "flock" instead. solves problem because based on open file descriptors. if process dies holding flock associated file descriptor automatically closed , hence free flock.
Comments
Post a Comment