Kajzer
Kajzer

Reputation: 2385

Semaphores and shared memory in linux

I have a bit of a problem at how to synchronize 2 processes. First process must create a shared memory, then wait for the second process to fill the shared memory and signalize it back to the first process. I don't know how to make the first process wait.

Here is a pseudocode of how my processes look like:

Process1:

create shared memory
create a semaphore
wait for the second process /* this part i dont know how to write */
output the shared memory

Process2:

get shared memory id
get the semaphore id
wait();
fill the shared memory 
signalize();

Upvotes: 3

Views: 5233

Answers (2)

Rohit J
Rohit J

Reputation: 82

You are correct so far.

As you mentioned in your question you are using semaphore that is the answer to your question.

In posix semaphore api, you have sem_wait() which will wait until value of the semaphore count is zero once it is incremented using sem_post from other process the wait will finish.

In this case you have to use 2 semaphores for synchronization.

process 1 (reader)
sem_wait(sem1);
.......

.......
sem_post(sem2);

process 2(writer)
sem_wait(sem2);
.......
.......
sem_post(sem1);

In this way you can achieve synchronization in shared memory.

Upvotes: 3

Raam
Raam

Reputation: 10886

This is hint and not an complete answer. Use condition variables. See https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables, that explains how it works. You can work out the solution from there.

Upvotes: 0

Related Questions