I have to synchronize N client processes with one server. These processes are forked by a main function in which I declared 3 semaphores. I decided to use POSIX semaphores but I don't know how to share them between these processes. I thought that shared memory should work correctly, but I have some questions:
sizeof(sem_t)
in size_t
field of shmget
in order to allocate exactly the space I need? If you specify a non-zero value for the pshared argument, the semaphore can be shared between processes. If you specify the value zero, the semaphore can be shared among threads of the same process. The sem_open function establishes a connection between a named semaphore and the calling process.
To declare a sem_t inside a shared memory segment, do this: /* shmPtr is a pointer to the base of your shared memory area */ sem_t *sem = (sem_t*)shmPtr; void *usableSharedMemory = (char*)shmPtr + sizeof(sem_t); .
Example: Using semaphore set and shared memory functionsThe buffer is a shared memory segment. The process synchronization is done using semaphores. Use the Create C Module (CRTCMOD) and the Create Program (CRTPGM) commands to create this program. Call this program with no parameters before calling the client program.
A semaphore lock on the shared memory buffer reference allows processes accessing the shared memory to prevent a daemon from writing to the memory segment currently being accessed.
It's easy to share named POSIX
semaphores
Choose a name for your semaphore
#define SNAME "/mysem"
Use sem_open
with O_CREAT
in the process that creates them
sem_t *sem = sem_open(SNAME, O_CREAT, 0644, 3); /* Initial value is 3. */
Open semaphores in the other processes
sem_t *sem = sem_open(SEM_NAME, 0); /* Open a preexisting semaphore. */
If you insist on using shared memory, it's certainly possible.
int fd = shm_open("shmname", O_CREAT, O_RDWR); ftruncate(fd, sizeof(sem_t)); sem_t *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); sem_init(sem, 1, 1);
I haven't tested the above so it could be completely bonkers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With