void cleanupsems(void) { int s; s = msemgrab(SEM0, 0); if (s != -1) { msemrm(s); } }
/** * Cleanup all ipc resources */ static void ipc_shutdown(void) { /* We need to block all signals to avoid race condition */ sigset_t blocked_signals; (void) sigfillset(&blocked_signals); (void) sigprocmask(SIG_BLOCK, &blocked_signals, NULL); /* cleanup has already been done */ if(cleanup == 1) { return; } cleanup = 1; /* If cnd has already been aquired, try to remove it (would return -1 if cnd had already been removed by other process) */ if(cnd != -1) { (void) msemrm(cnd); } /* detach SHM Segment (So it can be free'd later, or by other process) */ shm_detach(); if(mtx != -1) { /* This fails with -1 if onother process has already done the cleanup of smh segment */ if(semdown(mtx) != -1) { /* * It might happen, that we only fail to aquire shm segment, but have a working mtx. * In this case we will not destroy the mtx, because other processes might have created an shm segment and will therefor need a working mtx to free it. */ if(shm != -1) { (void) shmctl(shm, IPC_RMID, NULL); (void) semrm(mtx); } else { (void) semup(mtx); } } } }
int server(void) { int s = mseminit(SEM0, 0600, 2, 0, 1); if (s == -1) { perror("mseminit"); return 1; } int cnt = 1; for (int i = 0; i < 5; ++i) { if (mP(s, 1, 0) != 0) { if (errno == EINTR) { /* interrupted by syscall, try again */ continue; } perror("mP(0)"); break; } printf("s%d", cnt); cnt += 2; fflush(stdout); if (mV(s, 1, 1) != 0) { perror("mV(1)"); break; } } /* clean up semaphores */ if (msemrm(s) != 0) { perror("msemrm"); } return 0; }