Share unnamed semaphore between processes in Mac OS

659 views Asked by At

I'm trying to share a unnamed mach semaphore between two processes. I can create one and wait on it in the same process.

semaphore_t semaphore = 0;
mach_error_t err = semaphore_create(mach_task_self(), &semaphore, SYNC_POLICY_FIFO, 0);
...
semaphore_wait(semaphore);

But I want to send it to another process (of which I only have the mach_port_t) and then let it semaphore_signal my own process.

I already tried things like:

mach_port_allocate(target, MACH_PORT_RIGHT_RECEIVE, targetSemaphore)
mach_port_insert_right(target, targetSemaphore, semaphore, MACH_MSG_TYPE_COPY_SEND)

Which will yield an error because the port name already exists in the target process or a "unknown failure" if I don't allocate it in the target process.

And even:

mach_msg_send
mach_msg_receive

But I can't even get a port right form one process to anther to send anything.

What am I doing wrong and is it even possible?

1

There are 1 answers

1
Alexander Meißner On

I figured it out:

mach_port_extract_right

is correct way, instead of:

mach_port_insert_right

Then doing this, will do the job:

semaphore_t semaphore = 0;
mach_error_t err = semaphore_create(mach_task_self(), &semaphore, SYNC_POLICY_FIFO, 0);

err = mach_port_allocate(target, MACH_PORT_RIGHT_RECEIVE, &receivePort);

mach_msg_type_name_t type;
semaphore_t sendPort = 0;
err = mach_port_extract_right(target, receivePort, MACH_MSG_TYPE_MAKE_SEND, &sendPort, &type);

//Send semaphore using port
mach_msg_send(&msg.header);