I just recently found out about POSIX semaphores. POSIX semaphores are a way to synchronize access to shared resources between multiple processes. Supposedly, they are superior to traditional UNIX sempahores because they are more lightweight. However, there is frustratingly little online information about POSIX semaphores, so I'm not sure if I'm using them right.
I am wondering if any experts here have ever used POSIX semaphores before, or even heard of them? I experimented with them a little, and I seem to have them working right, but I'm not sure. Apparently, you need to place a semaphore in shared memory, and then it works kind of like a pthread_mutex in that you can lock it before accessing a critical section, and then unlock it when finished.
Here is the code:
int main() {
/* create shared memory region */
key_t segid = 50000;
int shmid;
shmid = shmget(segid, 1024, IPC_CREAT | 0660);
void* sh_mem = shmat(shmid, (void*) 0, 0);
/* create POSIX semaphore */
sem_t* sem = (sem_t*) sh_mem;
int sts = sem_init(sem, true, 1);
/* spawn a child process */
pid_t p = fork();
if (p > 0) {
sem_wait(sem);
printf("Parent: Sleeping for 2 seconds...\n");
sleep(2);
printf("Parent: Done sleeping...\n");
sem_post(sem);
}
else if (p == 0) {
sem_wait(sem);
printf("Child: Sleeping for 2 seconds...\n");
sleep(2);
printf("Child: Done sleeping...\n");
sem_post(sem);
}
}
I think I have it working correctly, because the output is correctly synchronized. But I'm not sure, and would like an expert to review the above code to see if I'm doing this correctly.
Start Free Trial