Home > database >  Win32: Is there an equivalent to POSIX sem_init?
Win32: Is there an equivalent to POSIX sem_init?

Time:09-10

POSIX anonymous semaphores allow me to create and use a semaphore in shared memory. This works great, because this means other processes that shouldn't have access to the semaphore don't have access to the semaphore. In addition, it's easy to incorporate into existing structures.

Does Windows offer something like this? The closest thing I've found is calling CreateSemaphore without a name, then having it inherited or DuplicateHandle()d to a child.

Edit: @IInspectable wanted me to give context. I'm planning to implement a sort of RPC system through shared memory. The data in shared memory looks like this:

struct shm_rpc_block {
  enum rpc_state {
    send = 0,
    receive
  };
  rpc_state state;
  sem_t lock;
  char data[2048 - sizeof(rpc_state) - sizeof(sem_t)];
};

The state variable begins in the "send" state. Process 1 writes its data to the data array, then changes the state to "receive" and unlocks, allowing process 2 to lock. Process 2 reads in the sent data, generates a response, then sends it back. The first process then reads the result, and resets the RPC state to "send".

CodePudding user response:

NO. You cannot specify a desired starting address for semaphore with WindowsAPI.
The document only states three ways to use semaphore between processes. A process can specify the name of a semaphore object in a call to the OpenSemaphore or CreateSemaphoreEx function besides the two ways you pointed.

  • Related