Shared Memory and Semaphores

I was writing a code and strangely I am getting some unexpected answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <assert.h>
#include "Semaphore.h"
#include "SharedMemory.h"

using namespace std;
int main()
{
    int i, *data, *count;
    Semaphore *sem, *semCount;
    SharedMemory *shm;
    SharedMemory *shm2;

    sem = new Semaphore(1);
    semCount = new Semaphore(1);
    shm = new SharedMemory(4096);
    shm2 = new SharedMemory(4);

    data = (int*)shm->Attach();
    count = (int *)shm2->Attach();
    *count = 0;

    for(i = 0; i < 1024; i++)
    {  
        sem->getLock();
        data[i] = getpid();
        sem->ReleaseLock();
    }
    semCount->getLock();
    *count = *count + 1;
    semCount->ReleaseLock();

    while(*count < 1)
    {}

    for(i = 0; i < 1024; i++)
    {
        sem->getLock();
        cout<<"PID:"<<getpid()<<" "<<i<<": "<<data[i]<<endl;
        sem->ReleaseLock();
    }

    shm->Detach((void *)data);
    shm2->Detach((void *)count);
    return 0;
}


And the result I am getting is:
PID:10275 0: 10276
PID:10275 1: 10275
PID:10275 2: 10275
PID:10275 3: 10275
.
.
.
.
.
PID:10275 1023: 10275

The pid stored in array location 0 is alway 1 greater than the other PID values. Why so??
getpid() is not defined in the scope of this forum, and I think your problem might lie there.

Oh, by the way, just curious, why are you using semaphores in this program? What other threads are accessing data?

EDIT: And what about your shared memory system? Perhaps shm->Attach() isn't working properly?

-Albatross
Last edited on
Hi Albatross,

Well the problem was that the second shared memory segment was getting attached to the one created earlier and it was incrementing the value of pid by one (*count = *count + 1). Hence I was getting one value greater than the actual pid.

Now, I have a new problem. I have 4 processes running this. When I am attempting to remove the shared memory region, it gives error if the region is already removed. How do I make sure that, it is not called if the region is already removed?

Thanks
Topic archived. No new replies allowed.